Django REST Framework:在嵌套对象中定义字段?
Posted
技术标签:
【中文标题】Django REST Framework:在嵌套对象中定义字段?【英文标题】:Django REST Framework: define fields in nested object? 【发布时间】:2013-02-26 01:57:23 【问题描述】:我收到了发生在地点的事件:
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"
,
但是,我不希望它获取所有字段,因为我不需要所有字段。如何定义应从嵌套对象中检索哪些字段?谢谢!
【问题讨论】:
【参考方案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')
【讨论】:
记录在哪里? 在序列化程序部分,“处理嵌套对象”:django-rest-framework.org/api-guide/relations/…【参考方案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')
【讨论】:
【参考方案3】:当我试图弄清楚如何在嵌套时仅从序列化程序中排除某些字段时,我发现了这个问题。看起来 Tasawer Nawaz 也有这个问题。您可以通过覆盖get_field_names
来做到这一点。这是一个基于 Tom Christie 回答的示例:
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:在嵌套对象中定义字段?的主要内容,如果未能解决你的问题,请参考以下文章
python django-rest-framework 3.3.3 更新嵌套序列化程序
在 Django REST Framework 中处理嵌套对象表示
Django REST Framework:在嵌套对象中定义字段?
需要 Django Rest Framework 嵌套序列化程序 = False 错误