我的orders
表中有一个名为subscription_id
的属性,它需要是一个整数。我使用的是MySQL 5.7。
我在peewee中将此属性定义为IntegerField((
但问题是subscription_id
的某些值是''
,而不是像200
、23045
等数字。
这是我的课:
import peewee as pw
# defining base model
class BaseModel(pw.Model):
class Meta:
database = db
# defining my class for orders table
class Orders(BaseModel):
subscription_id = pw.IntegerField()
customer_id = pw.IntegerField()
status = pw.TextField()
当在MySQL表中使用tb_orders.insert(orders).execute()
执行INSERT
时,当subscription_id
=''
时,在MySQL表中将其显示为0
,但我希望它为NULL
我该怎么做?
我试着设置一个默认值,比如:
class Orders(BaseModel):
subscription_id = pw.IntegerField(default=None)
customer_id = pw.IntegerField()
status = pw.TextField()
但没有奏效。
我找到了一个解决方案。首先,我将所有''
转换为None
:
for x in orders_ok:
if x['subscription_id'] == '':
x['subscription_id'] = None
之后,我在IntegerField((:中设置null=True
# defining my class for orders table
class Orders(BaseModel):
subscription_id = pw.IntegerField(null=True)
customer_id = pw.IntegerField()
status = pw.TextField()
现在NULL
出现在MySQL的subscription_id
属性中,而不是0
。