python - SQLAlchemy @property 在棉花糖中使用 dump_only 导致“未知字段”错误
问题描述
我正在使用烧瓶棉花糖(棉花糖=v3.0.0rc1,烧瓶棉花糖=0.9.0)和烧瓶sqlalchemy(sqlalchemy=1.2.16,烧瓶sqlalchemy=2.3.2)
我有这个模型和架构。
from marshmallow import post_load, fields
from .datastore import sqla_database as db
from .extensions import marshmallow as ma
class Study(db.Model):
_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
tests = db.relationship("Test", backref="study", lazy='select', cascade="all, delete-orphan")
@property
def test_count(self):
return len(self.tests)
class StudySchema(ma.ModelSchema):
test_count = fields.Integer(dump_only=True)
class Meta:
model = Study
sqla_session = db.session
schema = StudySchema()
payload = request.get_json()
schema.load(data=payload, instance=Study.query.get(payload["_id"]))
schema.session.commit()
如果我使用此有效负载执行 PUT 操作,则会
{'_id': 1, 'name': 'Study1', 'test_count': 0}
收到以下异常marshmallow.exceptions.ValidationError: {'test_count': ['Unknown field.']}
如果我删除了dump_only=True
这个异常AttributeError: can't set attribute
,这对我来说很有意义,因为它试图在模型类上设置 test_count 而没有 setter 方法。
我不明白的是为什么该属性不被忽略dump_only
。为什么当它被标记为时,棉花糖在加载期间仍然试图验证和理解这个字段dump_only
?
解决方案
在 marshmallow 2 中,未知或 dump_only 字段从输入中被忽略。除非用户决定将自己的验证添加到错误中。
在 marshmallow 3 中,我们将其更改为提供三种可能性(请参阅文档):
- 提高(默认)
- 排除(如棉花糖 2)
- INCLUDE(不经验证传递数据)
已经讨论了如何处理 dump_only 字段,我们得出的结论是,从客户的角度来看,这些应该被视为未知字段(请参阅https://github.com/marshmallow-code/marshmallow/issues/875)。
最重要的是,您的 PUT 有效负载不应包含 dump_only 字段。或者您可以将 EXCLUDE 策略设置为您的架构,但我更喜欢前一个选项。
推荐阅读
- c++ - 在 MFC 中设置边距长度的问题
- elasticsearch - 如何在kibana中搜索嵌套键
- r - 如何将自定义 ggplot 别名存储为 .R 脚本中的“列表”对象,并根据所需的标签向量获取它们
- c - 如何在 Openssl 引擎和 Openssl 软件实现之间动态切换?
- json - 带有 HTTP 数据库的 Flutter 下拉菜单
- javascript - 我正在使用 Strapi 构建 API,但 findone 总是返回 {}
- django - django如何创建用户实例
- jenkins - 通过 Jenkins 检查 Artifactory 中的路径是否存在
- javascript - 如何在不指定 Typescript 中的每个变量的情况下发布传递数据
- javascript - Nodejs发布文件