Django Rest Framework - Nested Serialization not working as expected

后端 未结 3 751
鱼传尺愫
鱼传尺愫 2021-02-07 17:32

While using Django-REST-Framework, I am not able to display selected fields in a nested serialized object.

I am correctly able to serialize the entirety of the Ad

3条回答
  •  春和景丽
    2021-02-07 17:48

    Try this:

    from rest_framework import serializers
    from api_v1.models import Outlet, Address
    
    class AddressSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Address
            fields = ('building', 'street',)
            depth = 3
    
    
    class OutletSerializer(serializers.ModelSerializer):
        address = AddressSerializer(many=False) # make it address, not outlet_address
    
        class Meta:
            model = Outlet
            fields = ('id', 'name', 'thumbnail', 'address') # make this address as well, not outlet_address
            depth = 3
    

    The reason I would make the changes above is because the Outlet model does not have an attribute called "outlet_address", it has an attribute called "address".

    See here for a similar issue: Django Rest framework keeps returning error on nested relationship

提交回复
热议问题