[Django]-Serializers in django rest framework with dynamic fields

0👍

Let’s take this step by step:

  1. In order to get a JSON like the one you posted, you must first transform your string (productConfig value field) to a dictionary. This can be done by using ast.literal_eval ( see more here).

Then, in your product serializer, you must specify the source for each field, like this:

class ProductSerializer(serializers.ModelSerializer):
    color = serializer.Field(source='value_dict.color')    
    size = serializer.Field(source='value_dict.size')
    type = serializer.Field(source='type.name')

class Meta:
    model = Product
    fields = (
        'id',
        'color',
        'size',
        'type',
    )

This should work just fine for creating the representation that you want. However, this will not create automatically the product config, because DRF doesn’t yet allow nested object creation.
This leads us to the next step:

  1. For creating a product with a configuration from JSON, you must override the post method in your view, and create it yourself. This part shouldn’t be so hard, but if you need an example, just ask.

  2. This is more of a suggestion: if the json fields are already defined, wouldn’t it be easier to define them as separate fields in your productConfig model?

👤AdelaN

Leave a comment