【问题标题】:Default value for peewee DoubleField doesn't get reflected in MySQL dbpeewee DoubleField 的默认值不会反映在 MySQL 数据库中
【发布时间】:2017-10-06 07:52:31
【问题描述】:

用例:想要将0.0 存储为默认值,而没有为peweeDoubleField 传递任何值。我编写了以下代码,但对我不起作用。

class MyRelation(peewee.Model):
    id = peewee.PrimaryKeyField()
    percentage = peewee.DoubleField(default=0.0)

这是一个api

@api_blueprint.route('/add_data', methods=['POST'])
@http_header
def add_data():
    try:
        incoming = json.loads(request.data)
        data = MyRelation(percentage=incoming["percentage"])
        data.save()

        return success_response(201,"Data has been inserted :)")

    except Exception as e:
        log(str(e))
        return raise_error(500, str(e))

记录以下错误

10-05-17 05:24:51 Line:199  Message: Error in add_data(),views.api: (1048, "Column 'percentage' cannot be null")

【问题讨论】:

    标签: python mysql flask flask-peewee


    【解决方案1】:

    差异仅在 Python 端强制执行——因此,如果您希望服务器强制执行默认设置,则需要使用约束:

    percentage = peewee.DoubleField(constraints=[SQL('DEFAULT 0.0')])
    

    文档:http://docs.peewee-orm.com/en/latest/peewee/models.html#default-field-values

    【讨论】:

    • 这里的SQL 是什么?看不懂这里[SQL('DEFAULT 0.0')]
    • from peewee import SQL -- 用peewee表示SQL文字。
    • 如果确实修改了 MySQL 结构但仍然抛出此错误。 @coleifer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多