10

在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, 
+0

不要以为这是关系到你的问题,但看起来像那些'exclude'选项缺少逗号,这会迫使他们被视为元组。 'exclude =('id',)' –

+0

另外请注意,您不需要'source ='type'',因为在这种情况下,字段名称已经匹配您要使用的源。 –

+0

@TomChristie是的,我已经尝试了第一个没有'source ='type'' –

回答

5

我不知道发生了什么事那里,我们有覆盖这个案件和类似的案件对我工作很好。

也许尝试放入shell并直接检查串行器。

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

例如:

serializer = ProductSerializer(data={'barcode': 'foo', 'type': None}) 
print serializer.is_valid() 
print serializer.errors 

如果你得到一些回答这些,更新的问题,我们会看到,如果我们可以得到它排序。

编辑

好吧,这解释了事情做得更好。 “类型”字段可以为空,因此它可能是None,但它仍然是必填字段。如果您希望它为空,则必须明确将其设置为None

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

+1

谢谢,我用shell的输出更新了这个问题。 –

+1

谢谢,向串行器添加'type = serializers.PrimaryKeyRelatedField(required = False)'有帮助。 (认为​​'null = True'的意思是相同的) –

+4

只是为了防止有人搜索到一个字段为空,并且还在这个线程中绊倒:如果你想明确地为一个PrimaryKeyRelatedField启用一个字段为空,你应该添加:allow_null = True :) – gabn88

6

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

相关问题