我正在尝试为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()方法之后运行单独的"alter table“查询。如果在peewee.FloatField本身无法做到这一点,那么我也会接受任何其他解决方案,只要它能确保create_tables()调用将以指定的精度创建列。
发布于 2021-05-11 02:45:38
正如@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)https://stackoverflow.com/questions/67475853
复制相似问题