2013-01-10 75 views
6

你如何在api中包含相關的字段?Django Rest框架 - 反向關係

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

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

每個Foo都有一些與他有關的酒吧,比如圖片或任何東西。

如何在Foo資源中顯示這些欄?

與tastypie其退出簡單,即時通訊和Django的REST框架不知道..

回答

8

我得到它的工作! Shweeet!

確定這就是我所做的:在酒吧對象

創建序列化,視圖和URL在Django REST框架的快速入門文檔描述。

然後在富串行我這樣做:

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 

Actualy其真正的簡單,文檔只是不表現得很好,我會說..

+0

這不適合我。我得到一個錯誤,說該網址無法解析。我在rest/urls.py文件中添加了url,它起作用。不知道我做錯了什麼。 – sweyrick

+3

只想說謝謝!!!!!!!有關這方面的文檔很糟糕。 – whoisearth

3

這些日子裏,你可以只是簡單的做到這一點將反向關係添加到fields元組。

你的情況:

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

現在-set將包含在你的富迴應 「欄」。

+0

我在做同樣的事情,在嵌套的響應,可以說有4個酒吧相關,然後我得到4空jsons,我不知道爲什麼這不起作用,計數工作正常 – Sugam