【问题标题】:Specify FLOAT column precision in Peewee with MariaDB/MySQL使用 MariaDB/MySQL 在 Peewee 中指定 FLOAT 列精度
【发布时间】:2021-08-01 04:14:18
【问题描述】:

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


【解决方案1】:

正如@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)

【讨论】:

  • 非常感谢,这正是我所需要的!我将看看是否有可能将此更改合并到库本身中
猜你喜欢
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 2016-04-12
  • 2012-07-18
  • 2020-01-08
相关资源
最近更新 更多