簡體   English   中英

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

[英]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字段接受的MD參數,以便使用我需要的精度參數創建列。 在使用以下創建表后,我可以在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM