[英]Nullable ForeignKey fields in Django REST framework
在Django REST框架(2.1.16)中,我有一個可以為空的FK字段type
的模型,但是POST創建請求提供400 bad request
,表示該字段是必需的。
我的模特是
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字段?
謝謝!
更新:從它給出的shell
>>> serializer = ProductSerializer(data={'barcode': 'foo', 'type': None})
>>> print serializer.is_valid()
True
>>>
>>> print serializer.errors
{}
但沒有type = None:
>>> 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,
初始化序列化allow_null
時添加kwarg allow_null
:
class ProductSerializer(serializers.ModelSerializer):
type = serializers.PrimaryKeyRelatedField(null=True, source='type', allow_null=True)
正如@ gabn88的評論中已經提到的那樣,但我認為它保證了它自己的答案。 (花了我一些時間,因為我在自己找到之后才閱讀該評論。)
我不確定那里發生了什么,我們已經覆蓋了這個案子,類似的案件對我來說很好。
也許嘗試直接進入shell並檢查序列化程序。
例如,如果您實例化序列化程序, serializer.fields
返回什么? serializer.field['type'].null
怎么樣serializer.field['type'].null
? 如果您直接在shell中將數據傳遞給序列化程序,您會得到什么結果?
例如:
serializer = ProductSerializer(data={'barcode': 'foo', 'type': None})
print serializer.is_valid()
print serializer.errors
如果您得到一些答案,請更新問題,我們將看看是否可以對其進行排序。
編輯
好的,這更好地解釋了事情。 'type'字段可以為空,因此它可以是None
,但它仍然是必填字段。 如果您希望它為null,則必須將其顯式設置為None
。
如果您確實希望在POST數據時能夠排除該字段,則可以在序列化程序字段中包含required=False
標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.