Django Rest Framework - 反向关系

Har*_*rry 7 django tastypie django-rest-framework

你如何在api中包含相关字段?

class Foo(models.Model):
    name = models.CharField(...)

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    description = models.CharField()
Run Code Online (Sandbox Code Playgroud)

每个Foo都有几个与他有关的Bar,比如图像或者什么.

如何在Foo的资源中显示这些Bar?

与tastypie它的退出简单,我不确定Django Rest Framework ..

Har*_*rry 8

我搞定了!Shweeet!

好的,这就是我做的:

为Django REST Framework的快速入门文档中描述的Bar对象创建了序列化程序,视图和URL.

然后在Foo Serializer中我这样做了:

class FooSerializer(serializers.HyperlinkedModelSerializer):
    # note the name bar should be the same than the model Bar
    bar = serializers.ManyHyperlinkedRelatedField(
        source='bar_set', # this is the model class name (and add set, this is how you call the reverse relation of bar)
        view_name='bar-detail' # the name of the URL, required
    )

    class Meta:
        model = Listing
Run Code Online (Sandbox Code Playgroud)

Actualy它真的很简单,文档只是不显示它我会说..

  • 只是想说谢谢!!!!!!! 关于这方面的文件很糟糕. (4认同)

Mar*_*ind 6

如今,您只需向fields元组添加反向关系即可实现这一点。

在你的情况下:

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = (
            'name', 
            'bar_set', 
        )
Run Code Online (Sandbox Code Playgroud)

现在“bar”-set 将包含在您的 Foo 响应中。