python - Peewee 在使用 IntegerField() 时使用 0 表示无效整数,但我希望将其设置为 NULL
问题描述
我的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()
在INSERT
MySQL 表中使用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()
但它没有用。
解决方案
我找到了解决方案。首先,我将所有人转换''
为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
.
推荐阅读
- c++ - 如何将此代码从 C 转换为 C++?
- python-2.7 - Glob 模块返回错误值
- python - 数据集查询、数据库还是在文件中搜索?
- java - 如何使 JavaFX 应用程序针对不同的屏幕分辨率自动调整大小
- java - java - 如何以最有效且不同步的方式在java中使用多个线程?
- matlab - 制作矩阵每一列但没有零元素的直方图
- javascript - 如何获取表格中的输入值?
- python - 卡住在python中将二进制转换为整数
- sparql - SPARQL:将 BGP 划分为多个组
- android - 当回收器视图放置在嵌套滚动视图中时,PagedListAdapter 获取所有项目