Django REST Framework: define fields in nested obj

2020-02-17 06:11发布

I got events that happen at locations:

class Event(models.Model):
    title = models.CharField(max_length=200)
    date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    date_start = models.DateTimeField('start date')
    date_end = models.DateTimeField('end date')
    def __unicode__(self):
        return self.title
    description = models.TextField()
    price = models.IntegerField(null=True, blank=True)
    tags = TaggableManager()
    location = models.ForeignKey(Location, blank=False)

class Location(models.Model):
    location_title = models.CharField(max_length=200)
    location_date_published = models.DateTimeField('published date',default=datetime.now, blank=True)
    location_latitude = models.CharField(max_length=200)
    location_longitude = models.CharField(max_length=200)
    location_address = models.CharField(max_length=200)
    location_city = models.CharField(max_length=200)
    location_zipcode = models.CharField(max_length=200)
    location_state = models.CharField(max_length=200)
    location_country = models.CharField(max_length=200)
    location_description = models.TextField()
    def __unicode__(self):
        return u'%s' % (self.location_title)

I can get the results of all via:

class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field()
    class Meta:
        model = Event
        depth = 2
        fields = ('url','id','title','date_start','date_end','description', 'price', 'location')

Which outputs:

 {
            "url": "http://localhost:8000/api/event/3/", 
            "id": 3, 
            "title": "Testing", 
            "date_start": "2013-03-10T20:19:00Z", 
            "date_end": "2013-03-10T20:19:00Z", 
            "description": "fgdgdfg", 
            "price": 10, 
            "location": {
                "id": 2, 
                "location_title": "Mighty", 
                "location_date_published": "2013-03-10T20:16:00Z", 
                "location_latitude": "37.767475", 
                "location_longitude": "-122.406878", 
                "location_address": "119 Utah St, San Francisco, CA 94103, USA", 
                "location_city": "San Francisco", 
                "location_zipcode": "94103", 
                "location_state": "California", 
                "location_country": "United States", 
                "location_description": "Some place"
            }
        }, 

However, I don't want it to grab all fields, as I don't need all of them. How can I define what fields should be retrieved from my nested object? Thanks!

3条回答
女痞
2楼-- · 2020-02-17 06:18

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')
查看更多
小情绪 Triste *
3楼-- · 2020-02-17 06:30

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')
查看更多
唯我独甜
4楼-- · 2020-02-17 06:31

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')
查看更多
登录 后发表回答