Home > Net >  Can DRF serializer combine a few fields into a nested JSON?
Can DRF serializer combine a few fields into a nested JSON?

Time:09-13

I have a model of a product for Internet shop. Can I write a serializer that will wrap up a few fields in a nested JSON? For example:

class Product(models.Model):
    product_type = models.CharField(
        choices=ProductType.choices, 
        max_length=20
        )
    vendor_code = models.CharField(max_length=20)
    name = models.CharField(
        max_length=100, 
        default=vendor_code
        )
    material = models.CharField(
        choices=Material.choices,
        max_length=20
    )
    coating = models.CharField(
        choices=Coating.choices,
        default=Coating.NO_COATING,
        max_length=20
    )
    gem_type = models.CharField(
        choices=GemType.choices,
        default=GemType.NO_GEM,
        max_length=20
    )
    gem = models.CharField(
        choices=Gem.choices,
        blank=True,
        null=True,
        max_length=20
    )

I want some fields combined into nested JSON when serializing:

{
    'product_type': ...,
    'vendor_code': ...,
    'characteristics': {
        'material': ...,
        'coating': ...,
        ...
}

Is it possible in DRF?

CodePudding user response:

what you can do is write a custom field like:

 class MySerializer(serializers.ModelSerializer):
       my_nested_field = serializers.SerializerMethodField()
       class Meta:
             fields = ['field_1', 'field_2', 'my_nested_field']
       
       def get_my_nested_field(self, obj):
           return {
             'field_1':obj['field_1'], 
             'field_2':obj['field_2']  
           }

you can use this custom field in model serializer or a normal serializer.

  • Related