[英]Specify FLOAT column precision in Peewee with MariaDB/MySQL
我正在尝试为 Peewee 中的列定义指定浮点精度,但在官方文档或github 问题中找不到如何执行此操作。
我的示例 model 如下:
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
和D
参数,以便使用我需要的精度参数创建列。 在使用以下创建表后,我可以在 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()
调用将创建具有指定精度的列。
正如@booshong 已经提到的
最简单的解决方案是对默认的FloatField
进行子类化,如下所示:
class CustomFloatField(FloatField):
def __init__(self, *args, **kwargs):
self.max_digits = kwargs.pop("max_digits", 7)
self.decimal_places = kwargs.pop("decimal_places", 4)
super().__init__(*args, **kwargs)
def get_modifiers(self):
return [self.max_digits, self.decimal_places]
然后像这样使用它
my_float_field = CustomFloatField(max_digits=2, decimal_places=2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.