【问题标题】:Django Rest Framework - Reverse relationsDjango Rest Framework - 反向关系
【发布时间】:2012-12-25 03:06:25
【问题描述】:

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

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

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    description = models.CharField()

每个 Foo 都有几个与他相关的 Bar,比如图像或其他任何东西。

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

用tastepie 很简单,我不确定Django Rest Framework..

【问题讨论】:

    标签: django django-rest-framework tastypie


    【解决方案1】:

    由于我有一个名为 FooSomething 的模型,我无法进行上述操作。

    我发现以下内容对我有用。

    # models.py
    
    class FooSomething(models.Model):
        name = models.CharField(...)
    
    class Bar(models.Model):
        foo = models.ForeignKey(FooSomething, related_name='foosomethings')
        description = models.CharField()
    
    # serializer.py
    
    class FooSomethingSerializer(serializers.ModelSerializer):
        foosomethings = serializers.StringRelatedField(many=True)
    
        class Meta:
            model = FooSomething
            fields = (
                'name', 
                'foosomethings', 
            )
    

    【讨论】:

      【解决方案2】:

      如今,您只需将反向关系添加到 fields 元组即可实现此目的。

      在你的情况下:

      class FooSerializer(serializers.ModelSerializer):
          class Meta:
              model = Foo
              fields = (
                  'name', 
                  'bar_set', 
              )
      

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

      【讨论】:

      • 我也在做同样的事情,在嵌套响应中,假设有 4 个相关条,然后我得到 4 个空 json,我不知道为什么这不起作用,计数工作正常跨度>
      • 如果bar 模型被称为SomethingBar 会发生什么? something_bar_setsomethingbar_set 都不起作用:(
      【解决方案3】:

      我搞定了!甜甜的!

      好的,这就是我所做的:

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

      然后在 Foo 序列化器中我这样做了:

      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
      

      实际上它真的很简单,我想说的是文档没有很好地展示它..

      【讨论】:

      • 这对我不起作用。我收到一条错误消息,提示无法解析 url。我已经在我的 rest/urls.py 中添加了 url,它可以工作。不知道我做错了什么。
      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 2013-10-20
      • 2015-12-14
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2014-03-21
      相关资源
      最近更新 更多