首页 > 解决方案 > 如何在 Flask-Marshmallow 中将整数字段设置为可选?

问题描述

我有以下模型及其相应的架构。如果我尝试将该字段留空,则字段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) 字段可选?

标签: pythonflaskmarshmallowmarshmallow-sqlalchemy

解决方案


我的猜测是您输入数据中的字段没有丢失,但是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)

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


推荐阅读