python - 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, 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 模型的序列化程序。

我试过了:

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 的帮助 :)

关于python - Django Rest Framework - 在序列化程序中获取相关模型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20633313/

相关文章:

python - 如何使 absolute_import 成为所有模块的默认值

python - 设置python路径

python - 在 Python 中生成随机十六进制颜色

c# - 使用 Protocol buffers/Protobuf 的 PInvoke 通用字符串格式

python - 如何在 Python 中使用 BLE 通知

python - Conda安装环境(PyFerret)不成功

php - Drupal PHP 序列化和反序列化

java - 如何序列化第三方不可序列化的最终类(例如谷歌的 LatLng 类)?

python - 用于进行更改的分而治之递归解决方案

django - 我对 app.py 中使用的就绪函数感到困惑