使用 MariaDB/MySQL 在 Peewee 中指定 FLOAT 列精度

Specify FLOAT column precision in Peewee with MariaDB/MySQL

我正在尝试为 Peewee 中的列定义指定浮点精度,但在 official docs or in the 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()

以上在数据库中创建了以下 table 规范:

SHOW COLUMNS FROM testmodel;
/*
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| value | float   | NO   |     | NULL    |                |
+-------+---------+------+-----+---------+----------------+
*/

我想要指定 FLOAT 字段接受的 M and D parameters,以便使用我需要的精度参数创建列。在 table 使用以下创建后,我可以在 SQL 中完成此操作:

ALTER TABLE testmodel MODIFY COLUMN value FLOAT(20, 6);  -- 20 and 6 are example parameters

这给出了这个 table 规格:

SHOW COLUMNS FROM testmodel;
/*
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| value | float(20,6) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
*/

但我希望它在 peewee 结构本身的 table 创建时间完成,而不是需要 运行 在 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)