本文介绍了Django Rest Framework - 在序列化程序中获取相关模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我正在尝试从 Django Rest 框架返回一个 HttpResponse,包括来自 2 个链接模型的数据.这些模型是:
I'm trying to return a HttpResponse from Django Rest Framework including data from 2 linked models. The models are:
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')
我想要一个包含来自相关 Wine 的信息的 Bottle 模型的序列化程序.
I'd like to have a serializer for the Bottle model which includes information from the related Wine.
我试过了:
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')
这不起作用.
有什么想法可以做到吗?
Any ideas how I could do that?
谢谢:)
推荐答案
就这么简单,将 WineSerializer 添加为字段即可解决.
Simple as that, adding the WineSerializer as a field solved it.
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 的帮助 :)
Thanks for the help @mariodev :)
这篇关于Django Rest Framework - 在序列化程序中获取相关模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!