当使用IntegerField()时,Peewee使用0表示无效整数,但我希望它设置为NULL



我的orders表中有一个名为subscription_id的属性,它需要是一个整数。我使用的是MySQL 5.7。
我在peewee中将此属性定义为IntegerField((
但问题是subscription_id的某些值是'',而不是像20023045等数字。

这是我的课:

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

最新更新