【发布时间】:2021-08-01 04:14:18
【问题描述】:
我正在尝试为 Peewee 中的列定义指定浮点精度,但在 official docs 或 github issues 中找不到如何执行此操作。
我的示例模型如下:
DB = peewee.MySQLDatabase(
"example",
host="localhost",
port=3306,
user="root",
password="whatever"
)
class TestModel(peewee.Model):
class Meta:
database = DB
value = peewee.FloatField()
以上在数据库中创建了以下表规范:
SHOW COLUMNS FROM testmodel;
/*
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| value | float | NO | | NULL | |
+-------+---------+------+-----+---------+----------------+
*/
我想要指定FLOAT 字段接受的M and D parameters,以便使用我需要的精度参数创建列。创建表后,我可以在 SQL 中完成此操作:
ALTER TABLE testmodel MODIFY COLUMN value FLOAT(20, 6); -- 20 and 6 are example parameters
这给出了这个表格规范:
SHOW COLUMNS FROM testmodel;
/*
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| value | float(20,6) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
*/
但我希望它在 peewee 结构本身内的表创建时完成,而不是在运行 peewee.Database.create_tables() 方法后需要运行单独的“更改表”查询。如果在 peewee.FloatField 本身中没有办法做到这一点,那么我也接受任何其他解决方案,只要它确保 create_tables() 调用将创建具有指定精度的列。
【问题讨论】:
-
您需要为此创建一个自定义字段。看看
DecimalField是如何在peewee中实现的,然后从那里开始
标签: python mariadb pymysql peewee