Python Django Rest Framework - 在序列化器中获取相关模型字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20633313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Rest Framework - Get related model field in serializer
提问by bpipat
I'm trying to return a HttpResponse from Django Rest Framework including data from 2 linked models. The models are:
我正在尝试从 Django Rest Framework 返回一个 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, 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')
I'd like to have a serializer for the Bottle model which includes information from the related Wine.
我想要一个 Bottle 模型的序列化程序,其中包含来自相关 Wine 的信息。
I tried:
我试过:
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')
which doesn't work.
这不起作用。
Any ideas how I could do that?
任何想法我怎么能做到这一点?
Thanks :)
谢谢 :)
采纳答案by bpipat
Simple as that, adding the WineSerializer as a field solved it.
就这么简单,添加 WineSerializer 作为一个字段解决了它。
class BottleSerializer(serializers.HyperlinkedModelSerializer):
wine = WineSerializer(source='wine')
class Meta:
model = Bottle
fields = ('url', 'wine', 'user', 'date_rated', 'rating', 'comment', 'get_more')
with:
和:
class WineSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Wine
fields = ('id', 'url', 'color', 'country', 'region', 'appellation')
Thanks for the help @mariodev :)
感谢@mariodev 的帮助:)
回答by Ryan Jeric
If you want to get specific field you can use Serializer Fields
如果你想获得特定的字段,你可以使用 Serializer Fields
https://www.django-rest-framework.org/api-guide/fields/
https://www.django-rest-framework.org/api-guide/fields/
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')

