ForeignKey不允许空值 [英] ForeignKey does not allow null values

查看:272
本文介绍了ForeignKey不允许空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django REST Framework 2.0。

I am using the Django REST Framework 2.0.

这是我的模型类:

class Mission(models.Model):
  assigned_to = models.ForeignKey('auth.User',
                                   related_name='missions_assigned',
                                   blank = True)

这是我的视图类:

class MissionList(generics.ListCreateAPIView):
    model = Mission
    serialize_class = MissionSerializer



  1. 多部分表单在浏览器中呈现,其中 assigned_to 字段为空选择。

何时发布原始JSON时,出现以下错误消息:

When posting raw JSON, I get the following error message:

无法分配无:" Mission.assigned_to不允许空值。

推荐答案

空白选项用于表单验证,而 null 用于写入数据库。

The blank option is used in the form validation, and the null is used when writing to database.

因此您可以在该字段中添加 null = True

So you might add null=True to that field.

编辑:

保存对象时考虑两个步骤:

Considering the two steps when saving object:


  1. Validator(由空白

  2. 数据库限制(由 null 控制)

  1. Validator(controlled by blank)
  2. Database limitation(controlled by null)

对于默认值选项,请使用 IntegerField 例如,

默认= 5,空白=真,空=假,即使您未分配值(具有 blank = True ),通过(2),因为它具有默认值(5)并写入 5 而不是到数据库。

blank = True,null = False ,通过(1),但不是(2),因为它试图写 None 到数据库。

For default option, take IntegerField for example,
default=5, blank=True, null=False, pass (1) even if you didn't assign a value(having blank=True), pass (2) because it has a default value(5) and writes 5 instead of None to DB.
blank=True, null=False, which pass (1) but not (2), because it attempts to write None to DB.

因此,如果要将字段设为可选,请使用 default = SOMETHING,blank = True, null = False blank = True,null = True

Thus, if you want to make a field optional, use either default=SOMETHING, blank=True, null=False or blank=True, null=True.

另一个例外是字符串型字段,例如 CharField

建议使用 blank = True 单独,将 null = False 留在后面。

这使字段成为字符串(> = 1个字符(s ))或空字符串('',且len()== 0),并且从不 None

Another exception is the string-like field, such as CharField.
It's suggested that use the blank=True alone, leaving null=False behind.
This makes a field either a string(>=1 char(s)) or a empty string('', with len()==0), and never None.

原因是,设置 null = True 时,状态未设置可能有两个值:空字符串和,这令人困惑(并可能导致错误)。

The reason is that when null=True is set, there will be two possible value for the state "unset": empty string and None, which is confusing(and might causing bugs).

这篇关于ForeignKey不允许空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆