Django REST框架:在嵌套对象中定义字段?

时间:2013-03-11 00:07:44

标签: django django-models django-rest-framework

我在地点发生了一些事件:

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)

我可以通过以下方式获得结果:

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

哪个输出:

 {
            "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"
            }
        }, 

但是,我不希望它抓住所有字段,因为我不需要全部字段。如何定义应从嵌套对象中检索哪些字段?谢谢!

3 个答案:

答案 0 :(得分:18)

序列化程序可以嵌套,所以做这样的事情......

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')

答案 1 :(得分:5)

我去过这个并没有得到完美的解决方案,但我做了一些你可以检查的东西。

此方法不会创建嵌套序列化程序

**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')

答案 2 :(得分:4)

当我试图弄清楚如何在嵌套时从串行器 中排除某些字段时,我发现了这个问题。看起来Tasawer Nawaz也有这个问题。你可以通过覆盖get_field_names来做到这一点。这是一个基于汤姆克里斯蒂答案的例子:

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')