首页 > 解决方案 > 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

标签: pythonflasksqlalchemyflask-sqlalchemymarshmallow

解决方案


在 marshmallow 2 中,未知或 dump_only 字段从输入中被忽略。除非用户决定将自己的验证添加到错误中。

在 marshmallow 3 中,我们将其更改为提供三种可能性(请参阅文档):

  • 提高(默认)
  • 排除(如棉花糖 2)
  • INCLUDE(不经验证传递数据)

已经讨论了如何处理 dump_only 字段,我们得出的结论是,从客户的角度来看,这些应该被视为未知字段(请参阅https://github.com/marshmallow-code/marshmallow/issues/875)。

最重要的是,您的 PUT 有效负载不应包含 dump_only 字段。或者您可以将 EXCLUDE 策略设置为您的架构,但我更喜欢前一个选项。


推荐阅读