在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,
不要以爲這是關係到你的問題,但看起來像那些'exclude'選項缺少逗號,這會迫使他們被視爲元組。 'exclude =('id',)' –
另外請注意,您不需要'source ='type'',因爲在這種情況下,字段名稱已經匹配您要使用的源。 –
@TomChristie是的,我已經嘗試了第一個沒有'source ='type'' –