ForeignKey 不允许空值 [英] ForeignKey does not allow null values
问题描述
我使用的是 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
多部分表单在浏览器中呈现,
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:
- 验证器(由
blank
控制) - 数据库限制(由
null
控制)
- Validator(controlled by
blank
) - 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=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 个字符),要么是一个空字符串('',与 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屋!