Django Rest框架 - 在序列化程序中获取相关模型字段 [英] Django Rest Framework - Get related model field in serializer

查看:94
本文介绍了Django Rest框架 - 在序列化程序中获取相关模型字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Django Rest框架返回一个HttpResponse,包括来自2个链接模型的数据。
模型是:

  class Wine(models.Model):

color = $ C
region = models.CharField(max_length = 100,blank = True)
country = models.CharField(max_length = 100,blank = $ b 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')

这不行。



任何想法我该怎么做?



感谢:)

解决方案

简单的说,将WineSerializer作为一个字段加以解决。

  class BottleSerializer(serializers.HyperlinkedModelSerializer):
wine = WineSerializer(source ='wine')

class Meta:
model = Bottle
fields =('url','wine','user','date_rated','rating','comment','get_more' b $ b

with:

  class WineSerializer(serializers.HyperlinkedModelSerializer):

class Meta:
model = Wine
fields =('id','url','color'国家','区域','名称')

感谢您的帮助@mariodev: p>

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

I'd like to have a serializer for the Bottle model which includes information from the related 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 :)

解决方案

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

with:

class WineSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Wine
        fields = ('id', 'url', 'color', 'country', 'region', 'appellation')

Thanks for the help @mariodev :)

这篇关于Django Rest框架 - 在序列化程序中获取相关模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆