如何在Flask-Marshmallow中设置Integer字段为可选?



我有以下模型及其相应的Schema。字段sold_price如果我试图让字段为空,则会导致问题。I将抛出错误"不是一个有效的整数",这在技术上是正确的,但我需要使该字段为可选/允许为空。

# 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)字段可选吗?

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

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

最新更新