10

在Django REST框架(2.1.16)中,我有一個可爲空的FK字段type的模型,但POST創建請求給出400 bad request,它表示該字段是必需的。Django REST框架中的可爲空的外鍵字段

我的模型是

class Product(Model): 
    barcode = models.CharField(max_length=13) 
    type = models.ForeignKey(ProdType, null=True, blank=True) 

和串是:

class ProductSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Product 
     exclude = ('id') 

我試圖明確添加type到串行像

class ProductSerializer(serializers.ModelSerializer): 
    type = serializers.PrimaryKeyRelatedField(null=True, source='type') 
    class Meta: 
     model = Product 
     exclude = ('id') 

和它沒有任何效果。

http://django-rest-framework.org/topics/release-notes.html#21x-series我看到有一個錯誤,但它被固定在2.1.7。

我應該如何更改序列化程序以正確處理我的FK字段?

謝謝!


UPDATE: 從殼它給

>>> serializer = ProductSerializer(data={'barcode': 'foo', 'type': None}) 
>>> print serializer.is_valid() 
True 
>>> 
>>> print serializer.errors 
{} 

但沒有類型=無:

>>> serializer = ProductSerializer(data={'barcode': 'foo'}) 
>>> print serializer.is_valid() 
False 
>>> print serializer.errors 
{'type': [u'This field is required.']} 
>>> serializer.fields['type'] 
<rest_framework.relations.PrimaryKeyRelatedField object at 0x22a6cd0> 
>>> print serializer.errors 
{'type': [u'This field is required.']} 

在這兩種情況下它給

>>> serializer.fields['type'].null 
True 
>>> serializer.fields['type'].__dict__ 
{'read_only': False, ..., 'parent': <prodcomp.serializers.ProductSerializer object at 0x22a68d0>, ...'_queryset': <mptt.managers.TreeManager object at 0x21bd1d0>, 'required': True, 
+0

不要以爲這是關係到你的問題,但看起來像那些'exclude'選項缺少逗號,這會迫使他們被視爲元組。 'exclude =('id',)' –

+0

另外請注意,您不需要'source ='type'',因爲在這種情況下,字段名稱已經匹配您要使用的源。 –

+0

@TomChristie是的,我已經嘗試了第一個沒有'source ='type'' –

回答

5

我不知道發生了什麼事那裏,我們有覆蓋這個案件和類似的案件對我工作很好。

也許嘗試放入shell並直接檢查串行器。

例如,如果你實例化串行器,serializer.fields返回什麼? serializer.field['type'].null怎麼樣?如果你直接在shell中將數據傳遞給串行器,你會得到什麼結果?

例如:

serializer = ProductSerializer(data={'barcode': 'foo', 'type': None}) 
print serializer.is_valid() 
print serializer.errors 

如果你得到一些回答這些,更新的問題,我們會看到,如果我們可以得到它排序。

編輯

好吧,這解釋了事情做得更好。 「類型」字段可以爲空,因此它可能是None,但它仍然是必填字段。如果您希望它爲空,則必須明確將其設置爲None

如果您確實希望在發佈數據時能夠排除該字段,則可以在序列化程序字段中包含required=False標誌。

+1

謝謝,我用shell的輸出更新了這個問題。 –

+1

謝謝,向串行器添加'type = serializers.PrimaryKeyRelatedField(required = False)'有幫助。 (認爲​​'null = True'的意思是相同的) –

+4

只是爲了防止有人搜索到一個字段爲空,並且還在這個線程中絆倒:如果你想明確地爲一個PrimaryKeyRelatedField啓用一個字段爲空,你應該添加:allow_null = True :) – gabn88

6

初始化序列化時添加kwarg allow_null

class ProductSerializer(serializers.ModelSerializer): 
    type = serializers.PrimaryKeyRelatedField(null=True, source='type', allow_null=True) 

如早已@ gabn88的評論中提及,但我認爲它值得自己的答案。 (花了我一些時間,因爲我只能給自己找出來後閱讀評論。)

http://www.django-rest-framework.org/api-guide/relations/

相關問題