Django Rest Framework - 在序列化器中获取相关的模型字段

时间:2013-12-17 11:48:52

标签: python django serialization foreign-keys django-rest-framework

我试图从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')

我想要一个瓶子模型的序列化器,其中包含来自相关葡萄酒的信息。

我试过了:

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

哪个不起作用。

我有什么想法可以做到这一点?

谢谢:)

2 个答案:

答案 0 :(得分:53)

如此简单,将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')

感谢@mariodev的帮助:)

答案 1 :(得分:2)

如果要获取特定字段,可以使用序列化器字段

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