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

查看:32
本文介绍了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";不允许空值.

推荐答案

表单验证使用blank选项,写入数据库时​​使用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. 验证器(由blank控制)
  2. 数据库限制(由null控制)
  1. Validator(controlled by blank)
  2. Database limitation(controlled by null)

对于default选项,以IntegerField为例,
default=5, blank=True, null=False,即使您没有赋值(具有blank=True),通过(1),通过(2)因为它有一个默认值 (5) 并将 5 而不是 None 写入 DB.
blank=True, null=False,它通过 (1) 而不是 (2),因为它试图将 None 写入 DB.

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=Falseblank=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 个字符),要么是一个空字符串('',与 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时,状态unset"将有两种可能的值:空字符串和None,令人困惑(并可能导致错误).

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天全站免登陆