首页 > 解决方案 > Peewee 在使用 IntegerField() 时使用 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()

INSERTMySQL 表中使用tb_orders.insert(orders).execute(), when subscription_id=时'',在 MySQL 表中它显示为0,但我希望它是NULL
我怎样才能做到这一点?

我尝试设置默认值,例如:

class Orders(BaseModel):
    subscription_id = pw.IntegerField(default=None)
    customer_id = pw.IntegerField()    
    status = pw.TextField()

但它没有用。

标签: pythonmysqlpeewee

解决方案


我找到了解决方案。首先,我将所有人转换''None

for x in orders_ok:
    if x['subscription_id'] == '':
        x['subscription_id'] = None

在此之后,我null=True在 IntegerField() 中设置:

# defining my class for orders table
class Orders(BaseModel):
    subscription_id = pw.IntegerField(null=True)
    customer_id = pw.IntegerField()    
    status = pw.TextField()

现在NULL出现在 MySQLsubscription_id属性中,而不是0.


推荐阅读