Django Rest Framework - Nested Serialization not working as expected

后端 未结 3 743
鱼传尺愫
鱼传尺愫 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:42

    Additionally to the other answers, I would like to add the following in case somebody lands here too.

    The nested serialization requires the field name to be in the model fields in order to work.

    In case that we need a reverse relation, then obviously there will be no such field in the model fields.

    For example, with the particular models in the question, this would happen if we needed to reference all outlets in the address serializer.

    Therefore we need to: (a) Either specify a related_name to the foreign key of the other model. This is where we would use outlet_address, as this is the related name of address field in outlet model.

    Or (b) if no related name then use the default Django name, appending _set to the model name (eg outlet_set.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-07 17:56

    Model Outlet has an "address" field, not an outlet_address. I would advise to set your serializer like this:

    class OutletSerializer(serializers.ModelSerializer):
        address = AddressSerializer(many=False)
    
        class Meta:
            model = Outlet
            fields = ('id', 'name', 'thumbnail', 'address')
            depth = 2
    
    0 讨论(0)
提交回复
热议问题