简体   繁体   中英

Can DRF serializer combine a few fields into a nested JSON?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM