nut*_*hip 20 python mysql django null
我已经看过所有类似的线程,阅读文档,并尝试了许多组合来存储空值,就像IntegerField在db中一样,每次都失败.
我正在使用MySQL.
我models.py定义了一个age=models.IntegerField()字段.我从csv文件填充db,有些单元格没有值.Django文档说:
Field.null
If True, Django will store empty values as NULL in the database. Default is False.
Note that empty string values will always get stored as empty strings, not as NULL.
Run Code Online (Sandbox Code Playgroud)
因为我正在使用IntegerField我想要一个空字符串(来自csv的空单元格)存储NULL在db中.因此,我(想)必须添加null=True到该age领域.实际上,我尝试了更多:
age=models.IntegerField()
age=models.IntegerField(null=True)
age=models.IntegerField(null=True, blank=True)
age=models.IntegerField(null=True, blank=True, default=None)
Run Code Online (Sandbox Code Playgroud)
每次我将空字符串插入到我得到的数据库中
ValueError: invalid literal for int() with base 10: ''
Run Code Online (Sandbox Code Playgroud)
有什么猜测我还能做什么?
Bur*_*lid 44
字符串不是整数; 并且空白字符串不是None或NULL.您需要做的是捕获字段为空的那些实例,然后将其转换为None.
foo = "something" # "something" is coming from your CSV file
try:
val = int(foo)
except ValueError:
# foo is something that cannot be converted to
# a number. It could be an empty string, or a
# string like 'hello'
# provide a default value
val = None
# Now use val to insert into the database
f = MyModel()
f.age = val
f.save()
Run Code Online (Sandbox Code Playgroud)
blank严格用于前端验证; 它对数据库方面没有任何影响:
请注意,这与...不同
null.null纯粹与数据库相关,而blank与验证相关.如果字段有blank=True,则表单验证将允许输入空值.如果字段有blank=False,则需要该字段.
null 另一方面,与数据库有关:
如果为True,Django将在数据库中将空值存储为NULL.默认值为False.
的IntegerField要求,可以转换成一个整数值,所以当你在一传空字符串,它不能施放它,会引发异常.相反,如果你传入None,并且你有age = models.IntegerField(null=True),它知道正确存储它.
总结一下:
age = models.IntegerField()
字段是必需的,需要一个有效的整数值.它不会接受None并且在数据库中没有空值.有效值为-2147483648至2147483647
age = models.IntegerField(null=True)
需要字段(表单验证).如果该字段具有None值,则将其转换为NULL数据库中的值.
age = models.IntegerField(blank=True, null=True)
不需要字段(表单验证).如果传入该字段None,则将其转换为NULL
age = models.IntegerField(blank=True)
字段不是必需的(表单验证),但需要传入有效的整数值,因为数据库不接受null.通常在这里,您可以default=0在将值提交给orm之前为其提供默认值或进行一些验证.
| 归档时间: |
|
| 查看次数: |
23301 次 |
| 最近记录: |