【问题标题】:How to set Integer field to optional in Flask-Marshmallow?如何在 Flask-Marshmallow 中将整数字段设置为可选?
【发布时间】:2021-03-02 16:39:18
【问题描述】:

我有以下模型及其相应的架构。如果我尝试将该字段留空,则该字段 sold_price 会导致问题。我提出了错误“不是有效的整数”,这在技术上是正确的,但我需要将该字段设为可选/允许为空。

# Models.py
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    sold_price = db.Column(db.Integer)

# Marshmallow
class ProductSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Product
    id = auto_field(dump_only=True)
    sold_price = auto_field()

我设法找到了一个次优的解决方案,但我觉得必须有更好的方法。次优解决方案会影响自定义字段:

class OptionalInteger(fields.Field):

    def _serialize(self, value, attr, obj, **kwargs):
        if value is None:
            return ''
        return value

    def _deserialize(self, value, attr, data, **kwargs):
        if value:
            try:
                return int(value)
            except ValueError as error:
                raise ValidationError("Must a integer") from error
        return value

还有其他想法如何使 sold_price (int) 字段成为可选字段吗?

【问题讨论】:

标签: python flask marshmallow marshmallow-sqlalchemy


【解决方案1】:

我的猜测是您输入数据中的字段没有丢失,而是 null。这是字段留空的典型 HTML 表单。

默认情况下,DB字段不可为空,所以生成的字段

  • 不需要 (required = False)
  • 允许None (allow_none = True)

这发生在这里:https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/6e43a8357a012fb08ee1ec32e67c07679a97b917/src/marshmallow_sqlalchemy/convert.py#L264-L266

你可以通过打印来检查

print(ProductSchema().fields['sold_price'].required)
print(ProductSchema().fields['sold_price'].allow_none)

如果没有显示验证错误的代码示例,我无法解释您的问题。

【讨论】:

    猜你喜欢
    • 2018-10-28
    • 2023-03-17
    • 2021-07-12
    • 1970-01-01
    • 2016-05-29
    • 2022-06-30
    • 2019-11-17
    • 2016-12-03
    • 1970-01-01
    相关资源
    最近更新 更多