[Fixed]-Django REST Framework: define fields in nested object?

27👍

Serializers can be nested, so do something like this…

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = (...)

class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field()
    location = LocationSerializer()

    class Meta:
        model = Event
        fields = ('url','id','title','date_start','date_end','description', 'price', 'location')

8👍

I have been to this and did not get a perfect solution, But I did something you may check for it.

This method will not create nested serializers

**class LocationSerializer(serializers.ModelSerializer):**
     class Meta:
          model = Location
          fields = (...)       #does not matter
          exclude = (...)      #does not matter

class EventSerializer(serializers.ModelSerializer):**
    loc_field_1 = serializers.CharField(required=False,*source='location.loc_field_1'*)
    loc_field_2 = serializers.CharField(required=False,*source='location.loc_field_2'*)

    ***#ADD YOUR DESIRE FIELD YOU WANT TO ACCESS FROM OTHER SERIALIZERS***


    class Meta:
        model = Event
        fields =('url','id','title','date_start','date_end','description', 'price', 'location')

8👍

I found this question when I was trying to figure out how to exclude certain fields from a serializer only when it was being nested. Looks like Tasawer Nawaz had that question as well. You can do that by overriding get_field_names. Here’s an example based on Tom Christie’s answer:

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = (...)
        exclude_when_nested = {'location_title', 'location_date_published'}  # not an official DRF meta attribute ...

    def get_field_names(self, *args, **kwargs):
        field_names = super(LinkUserSerializer, self).get_field_names(*args, **kwargs)
        if self.parent:
            field_names = [i for i in field_names if i not in self.Meta.exclude_when_nested]
        return field_names

class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field()
    location = LocationSerializer()

    class Meta:
        model = Event
        fields = ('url','id','title','date_start','date_end','description', 'price', 'location')

Leave a comment