21

在 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 字段?

谢谢!


更新:从它给出的外壳

>>> 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, 
4

2 回答 2

17

allow_null在初始化序列化程序时添加 kwarg :

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

正如@gabn88 的评论中已经提到的,但我认为它需要自己的答案。(花了我一些时间,因为我只是在自己发现后才阅读该评论。)

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

于 2015-08-04T17:23:31.697 回答
8

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

也许尝试进入 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在序列化器字段中包含该标志。

于 2013-01-17T16:13:32.013 回答