2016-06-12 81 views
5

Bar具有Foo的ForeignKey,很多Bar to one Foo。在Django中使用表格,foreign key defaults to a select list input在Django Rest框架中下拉外鍵選擇

我想在Django Rest Framework中使用此功能,首先使用Browsable API,然後使用Template HTML Renderer。我已經超過nested relations in the docs,也看過this related question,但它沒有任何意義。至少它確實讓我覺得,我應該看到像股票Django Forms一樣的下拉行爲。

最終我想辦法讓創建時,我們選擇現有美孚/更新酒吧我相信我會通過手TemplateHTMLRenderer做到各具特色,改變表單字段的完整JSON數據的形式,即一個新的酒吧那就是指向現有的Foo,假設我在Bar上編寫更新和創建方法。但是這聽起來像我在某個地方錯過了「簡單的方法」。

class BarSerializer(serializers.ModelSerializer): 

    # This shows Foo.foo within serialzied Bar JSON: 
    # I suspect I am missing something with the relation that would allow me to select foo from a list 
    foo = serializers.SlugRelatedField(many=False, read_only=True,slug_field="foo") 


    class Meta: 
      model = Bar 
      fields = ('foo','some_value','another_value') 


class FooSerializer(serializers.ModelSerializer): 
    owner = serializers.ReadOnlyField(source='owner.username') 

    # This shows the Bar serialized within the Foo JSON i.e. nested serialization 
    bars = BarSerializer(many=True); 

    # reverse rel: related_name='bars' in Foo model 
    class Meta: 
     model = Foo 
     # 'bars' is the related name pointing from bar to foo 
     fields = ('bars', 'foo', 'owner') 

我知道要保存嵌套數據,我的序列化程序需要更新和創建。現在就實施這個。但是我無法擺脫困境,如何讓DRF填充選擇輸入並顯示Foo選項?

我錯過了一些明顯的是的?這裏來的RTFM(再次)downvotes:/

回答

1

這是五個月前,所以你可能有現在的答案,但我的谷歌搜索帶我到這裏開始。

所以櫃面你或其他人發生得的在這裏,我找到了答案,最好的工作是:

Django admin foreign key dropdown with custom value

基本上你需要告訴它以兩種方式之一場/字段作爲使用的下拉字符串。