python - 如何在 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) 字段可选?
解决方案
我的猜测是您输入数据中的字段没有丢失,但是null
. 这是字段留空的典型 HTML 表单。
默认情况下,DB字段不可为空,所以生成的字段
- 不需要 (
required = False
) - 允许
None
(allow_none = True
)
您可以通过打印检查
print(ProductSchema().fields['sold_price'].required)
print(ProductSchema().fields['sold_price'].allow_none)
如果没有显示验证错误的代码示例,我无法解释您的问题。
推荐阅读
- sql - 如何使用 SQL 查询在不同的行中打印结果?
- c - malloc 错误,我无法理解使用带有单独链接的哈希表
- reactjs - reactjs 如何根据从服务器获取的数据显示其他文本
- uiwindow - iOS13中具有多个窗口场景的最顶级视图控制器
- r - R获取并约束局部最大值位置和值的数量
- c++ - 调用 (list 和 push_front) 没有匹配的函数
- bash - 如何在逗号分隔符和自动增量之前替换数字
- android-studio - 将我的 Android Studio 项目连接到 Firebase 时出错
- alfresco - Activiti Timer 任务电子邮件 任务提醒通知
- sql - 我怎样才能找到在注册成为商店会员的前 90 天内进行交易的客户百分比?