Django REST框架中的Nullable ForeignKey字段

Dmi*_*kiy 15 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)
Run Code Online (Sandbox Code Playgroud)

和序列化器是:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        exclude = ('id')
Run Code Online (Sandbox Code Playgroud)

我试图type明确地添加到序列化器

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

它没有任何效果.

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
{}
Run Code Online (Sandbox Code Playgroud)

但没有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.']}
Run Code Online (Sandbox Code Playgroud)

它给出了两种情况

>>> 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, 
Run Code Online (Sandbox Code Playgroud)

Ris*_*nha 13

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

class ProductSerializer(serializers.ModelSerializer):
    type = serializers.PrimaryKeyRelatedField(null=True, source='type', allow_null=True)
Run Code Online (Sandbox Code Playgroud)

正如@ gabn88的评论中已经提到的那样,但我认为它保证了它自己的答案.(花了我一些时间,因为我在自己找到之后才阅读该评论.)

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


Tom*_*tie 6

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

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

例如,如果您实例化序列化程序,serializer.fields返回什么?怎么样serializer.field['type'].null?如果您直接在shell中将数据传递给序列化程序,您会得到什么结果?

例如:

serializer = ProductSerializer(data={'barcode': 'foo', 'type': None})
print serializer.is_valid()
print serializer.errors
Run Code Online (Sandbox Code Playgroud)

如果您得到一些答案,请更新问题,我们将看看是否可以对其进行排序.

编辑

好的,这更好地解释了事情.'type'字段可以为空,因此它可能是None,但它仍然是必填字段.如果您希望它为null,则必须将其显式设置为None.

如果您确实希望能够在POST数据时排除该字段,则可以required=False在序列化程序字段中包含该标志.

  • 以防万一有人正在搜索null字段并且偶然发现这个线程:如果你想明确地允许一个字段为PrimaryKeyRelatedField可以为空,你应该添加:allow_null = True :) (9认同)