Python Django Rest框架-在序列化程序中获取相关模型字段
我试图从Django Rest框架返回一个HttpResponse,其中包含来自2个链接模型的数据。 这些模型是:Python Django Rest框架-在序列化程序中获取相关模型字段,python,django,serialization,foreign-keys,django-rest-framework,Python,Django,Serialization,Foreign Keys,Django Rest Framework,我试图从Django Rest框架返回一个HttpResponse,其中包含来自2个链接模型的数据。 这些模型是: class Wine(models.Model): color = models.CharField(max_length=100, blank=True) country = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, bla
class Wine(models.Model):
color = models.CharField(max_length=100, blank=True)
country = models.CharField(max_length=100, blank=True)
region = models.CharField(max_length=100, blank=True)
appellation = models.CharField(max_length=100, blank=True)
class Bottle(models.Model):
wine = models.ForeignKey(Wine, null=False)
user = models.ForeignKey(User, null=False, related_name='bottles')
我想有一个瓶子模型的序列化程序,其中包括来自相关葡萄酒的信息
我试过:
class BottleSerializer(serializers.HyperlinkedModelSerializer):
wine = serializers.RelatedField(source='wine')
class Meta:
model = Bottle
fields = ('url', 'wine.color', 'wine.country', 'user', 'date_rated', 'rating', 'comment', 'get_more')
这不管用
你知道我该怎么做吗
谢谢:)就这么简单,添加WineSerializer作为字段解决了这个问题
class BottleSerializer(serializers.HyperlinkedModelSerializer):
wine = WineSerializer(source='wine')
class Meta:
model = Bottle
fields = ('url', 'wine', 'user', 'date_rated', 'rating', 'comment', 'get_more')
与:
class WineSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Wine
fields = ('id', 'url', 'color', 'country', 'region', 'appellation')
感谢@mariodev:)的帮助。如果您想获取特定字段,可以使用序列化器字段
谢谢你,我就快到了。@tom christie解释的内容可以获取对象本身,但我无法从Wine对象获取所有字段。请尝试将
source='*'
作为RelatedField
参数。我仍然可以在查询结果中获取unicode名称。在字段中尝试wine.color不起作用source='*'改变了什么?很高兴你能解决这个问题。您还可以解释一下WineSerializer类代表什么,所以我们有一个明确的答案..我已经这样做了,但是我得到了一个附带的错误HyperlinkedRelatedField需要序列化程序上下文中的请求。在实例化序列化程序时添加上下文={'request':request}
。我做错了什么?出现了这样的错误:AssertionError(u“HyperlinkedEntityField
需要序列化程序上下文中的请求。在实例化序列化程序时添加context={'request':request}
”)不是JSON序列化的。您不应该需要source='wine'
参数,因为它与名称相同。事实上,如果您没有因此而得到运行时错误,我会感到惊讶。相反,您可以添加其他参数,如(many=False,read_only=True)
,这将在wine
属性下生成一个嵌入对象。是否有办法从直接嵌入顶层对象的相关Wine
模型中获取特定字段?对于花费太长时间试图弄清楚如何链接到相关序列化程序的其他人,source=“Wine.color”遵循模型中定义的外键关系。在本例中,外键名为“wine”,相关字段为“color”。
class BottleSerializer(serializers.HyperlinkedModelSerializer):
winecolor = serializers.CharField(read_only=True, source="wine.color")
class Meta:
model = Bottle
fields = ('url', 'winecolor', 'user', 'date_rated', 'rating', 'comment', 'get_more')