Django的REST框架:定义嵌套的对象领域?(Django REST Framework: de

2019-07-21 07:32发布

我得到了发生在地点的事件:

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

不过,我不希望它抓住所有领域,因为我并不需要所有的人。 我怎样才能界定哪些领域应该从我的嵌套的对象进行检索? 谢谢!

Answer 1:

串行器可以被嵌套,所以做这样的事情...

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


Answer 2:

我到过这一点,并没有得到一个完美的解决方案,但我做了一件你可以检查它。

这种方法不会创建嵌套序列化

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


Answer 3:

我发现当我试图找出如何从在被嵌套它串行排除某些领域这个问题。 看起来Tasawer纳瓦兹有这样的问题也是如此。 您可以通过重写做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')


文章来源: Django REST Framework: define fields in nested object?