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 :)

相关文章