Django REST框架中的Nullable ForeignKey字段

时间:2013-01-17 15:17:38

标签: django null foreign-key-relationship 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, 

2 个答案:

答案 0 :(得分:9)

初始化序列化程序时添加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/

答案 1 :(得分:5)

我不确定那里发生了什么,我们已经覆盖了那个案子,类似的案件对我来说很好。

也许尝试直接进入shell并直接检查序列化程序。

例如,如果您实例化序列化程序,serializer.fields会返回什么? 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标记。