You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Peewee IntegerField插入空字符串存为0,如何改为NULL?

这个问题我之前也碰到过,原因其实很清楚——你设置的default=None只在没有提供该字段值的时候才会生效,但现在你明确传了空字符串'',MySQL的整数字段会把空字符串隐式转换为0,所以这个默认值参数根本没起作用。给你几个可行的解决办法:

方法一:插入前预处理数据(最简单直接)

在执行插入操作前,遍历你的数据列表,把所有值为''subscription_id替换成None,这样Peewee会自动把None转换成MySQL的NULL

# 假设orders是你要插入的字典列表
for order in orders:
    if order.get('subscription_id') == '':
        order['subscription_id'] = None

# 正常执行插入即可
tb_orders.insert(orders).execute()

方法二:自定义IntegerField自动处理空字符串

如果不想每次插入都手动改数据,可以自定义一个字段类型,让它自动把空字符串转为None,一劳永逸:

import peewee as pw

class NullableIntegerField(pw.IntegerField):
    def db_value(self, value):
        # 遇到空字符串就返回None,其他情况按原逻辑处理
        if value == '':
            return None
        return super().db_value(value)

# 在模型中使用自定义字段,注意必须加null=True(允许字段存NULL)
class Orders(BaseModel):
    subscription_id = NullableIntegerField(null=True)
    customer_id = pw.IntegerField()
    status = pw.TextField()

方法三:用Peewee信号全局处理

利用Peewee的预保存信号,在数据插入前自动修正字段值,适合需要全局统一处理模型的场景:

from peewee import signals

@signals.pre_save.connect(sender=Orders)
def handle_subscription_id(sender, instance, created):
    # 只在新增数据时处理,避免更新时误改
    if created and instance.subscription_id == '':
        instance.subscription_id = None

# 之后正常执行插入即可
tb_orders.insert(orders).execute()

重要注意点

别忘了检查你的MySQL表结构:确保subscription_id字段是允许为NULL的(也就是表结构里是INT NULL而非INT NOT NULL)。如果之前是不允许NULL的,可以用这条SQL修改:

ALTER TABLE orders MODIFY COLUMN subscription_id INT NULL;

内容的提问来源于stack exchange,提问作者igorkf

火山引擎 最新活动