如何在flask_marshmallow的SQLAlchemyAutoSchema中设置所有字段为必填?
如何让SQLAlchemyAutoSchema生成的所有字段设为必填?
我正在使用SQLAlchemyAutoSchema为模型自动生成字段,默认情况下它将所有字段的required状态设置为False。请问如何将所有字段设置为必填?
当前代码:
class ReferralOuctomeSchema(ma.SQLAlchemyAutoSchema): class Meta: model = my_model dump_only = ("id",) required = True
你当前代码里Meta类中的required=True参数无效,SQLAlchemyAutoSchema并不支持这个配置项。要实现所有字段设为必填,可参考以下两种方法:
方法1:基于模型字段的nullable属性自动映射
SQLAlchemyAutoSchema默认会根据模型中字段的nullable=False,自动将对应Schema字段的required设为True。如果你的模型字段已设置nullable=False但未生效,可在Meta类中添加include_fk=True(涉及外键字段时),同时确保模型定义正确。
示例模型定义:
class MyModel(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) email = db.Column(db.String(100), nullable=False)
对应Schema会自动将name和email标记为必填字段。
方法2:强制所有非dump_only字段为必填(忽略模型nullable设置)
如果需要忽略模型的nullable配置,强制所有非dump_only的字段为必填,可以重写Schema的get_field_kwargs方法:
class ReferralOuctomeSchema(ma.SQLAlchemyAutoSchema): class Meta: model = my_model dump_only = ("id",) def get_field_kwargs(self, field_name, model_field): kwargs = super().get_field_kwargs(field_name, model_field) # 跳过dump_only字段,其余字段强制设为必填 if field_name not in self.Meta.dump_only: kwargs["required"] = True return kwargs
此方式会将除id外的所有自动生成字段设为必填项。
内容的提问来源于stack exchange,提问作者Ayaz49
相关产品推荐
相关产品推荐

