Python 如何将空值存储为整数字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20399717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store empty value as an Integerfield
提问by nutship
I've seen all the similar threads, read the docs, and tried many combinations to store an empty value as IntegerFieldin db and failed every single time.
我看过所有类似的线程,阅读文档,并尝试了许多组合来存储一个空值,就像IntegerField在 db 中一样,但每次都失败了。
I am using MySQL.
我正在使用 MySQL。
My models.pydefines an age=models.IntegerField()field. I populate db from csv file, and some cells have no value. Django docs says:
Mymodels.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.
Since I am working with IntegerFieldI want an empty string (an empty cell from the csv) to be stored as NULLin db. Therefore, I (think) have to add null=Trueto the agefield. Actually, I've tried more than this:
由于我正在使用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)
and every time I am inserting an empty string to a db I got
每次我向数据库插入一个空字符串时,我都会得到
ValueError: invalid literal for int() with base 10: ''
Any guess what else can I do?
猜猜我还能做什么?
采纳答案by Burhan Khalid
A string is not an integer; and a blank string is not Noneor NULL. What you need to do is catch those instances where the field is blank and then cast it to None.
字符串不是整数;并且空白字符串不是Noneor 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()
blankis strictly for front end validation; it doesn't have any impact on the database side:
blank严格用于前端验证;它对数据库端没有任何影响:
Note that this is different than
null.nullis purely database-related, whereasblankis validation-related. If a field hasblank=True, form validation will allow entry of an empty value. If a field hasblank=False, the field will be required.
请注意,这与
null.null纯粹与数据库相关,而blank与验证相关。如果字段具有blank=True,则表单验证将允许输入空值。如果字段具有blank=False,则该字段将是必需的。
nullon the other hand, has to do with the database:
null另一方面,与数据库有关:
If True, Django will store empty values as NULL in the database. Default is False.
如果为 True,Django 将在数据库中将空值存储为 NULL。默认值为假。
An IntegerFieldrequires value that can be converted into an integer, so when you pass in a blank string, it cannot cast it and raises an exception. Instead, if you pass in None, and you have age = models.IntegerField(null=True), it knows to store it correctly.
AnIntegerField需要可以转换为整数的值,因此当您传入一个空白 string 时,它无法转换它并引发异常。相反,如果您传入None并且您有age = models.IntegerField(null=True),它就会知道正确存储它。
To summarize:
总结一下:
age = models.IntegerField()Field is required and needs a valid integer value. It will not accept
Noneand will have no null values in the database. Valid values are -2147483648 to 2147483647age = models.IntegerField(null=True)Field is required (form validation). If the field has
Noneas a value, it will be translated toNULLin the database.age = models.IntegerField(blank=True, null=True)Field is not required (form validation). If the field is passed in
None, it will be translated toNULLage = models.IntegerField(blank=True)Field is not required (form validation), but a valid integer value needs to be passed in because the database does not accept null. Typically here you would give it a default value with
default=0or have some validation done before submitting the value to the orm.
age = models.IntegerField()字段是必需的,需要一个有效的整数值。它不会接受
None并且在数据库中不会有空值。有效值为 -2147483648 到 2147483647age = models.IntegerField(null=True)字段是必需的(表单验证)。如果该字段具有
None值,它将NULL在数据库中转换为。age = models.IntegerField(blank=True, null=True)不需要字段(表单验证)。如果传入该字段
None,它将被转换为NULLage = models.IntegerField(blank=True)字段不是必需的(表单验证),但需要传入一个有效的整数值,因为数据库不接受空值。通常在这里你会给它一个默认值,
default=0或者在将值提交给 orm 之前完成一些验证。
回答by ndpu
Try to pass Noneto this field not empty string ''
尝试传递None给该字段的不是空字符串 ''
回答by Simon Chen
You can override 'clean' method in your form class, then cleaning the integer data for avoiding empty string to be submitted, see below example:
您可以在表单类中覆盖 'clean' 方法,然后清除整数数据以避免提交空字符串,请参见下面的示例:
def clean(self):
self.cleaned_data = super(YourForm, self).clean()
if self.cleaned_data['age'] == '': self.cleaned_data['age'] = None
return self.cleaned_data

