问题描述
我正在使用flask-marshmallow(marshmallow = v3.0.0rc1,flask-marshmallow = 0.9.0)和flask-sqlalchemy(sqlalchemy = 1.2.16,flask-sqlalchemy = 2.3.2)
I'm using flask-marshmallow (marshmallow=v3.0.0rc1, flask-marshmallow=0.9.0) and flask-sqlalchemy (sqlalchemy=1.2.16, flask-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.']}
If I perform a PUT operation with this payload{'_id': 1, 'name': 'Study1', 'test_count': 0}
I get the following exception marshmallow.exceptions.ValidationError: {'test_count': ['Unknown field.']}
如果我删除了dump_only=True
,我会得到这个异常AttributeError: can't set attribute
,这对我来说很有意义,因为它试图在模型类上设置不带setter方法的test_count.
If I remove the dump_only=True
I get this exception AttributeError: can't set attribute
which makes sense to me because it's trying to set test_count with no setter method on model class.
我不明白的是为什么dump_only
不能忽略该属性.为什么棉花糖在加载过程中仍标记为dump_only
时仍尝试验证并理解该字段?
What I do not understand is why is the attribute is not ignored with dump_only
. Why is marshmallow still trying to validate and understand this field during load when it's marked as dump_only
?
推荐答案
在棉花糖2中,未知或dump_only字段将从输入中忽略.除非用户决定对错误添加自己的验证.
In marshmallow 2, unknown or dump_only fields are ignored from input. Unless the user decides to add his own validation to error on them.
在棉花糖3中,我们将其更改为提供三种可能性(请参见文档):
In marshmallow 3, we changed that to offer three possibilities (see docs):
- RAISE(默认)
- 排除(如棉花糖2)
- INCLUDE(不通过验证即可传递数据)
已经讨论了如何处理dump_only字段,我们得出的结论是,从客户端的角度来看,应该将这些字段视为未知字段(请参阅 https://github.com/marshmallow-code/marshmallow/issues/875 ).
There's been discussions about how to deal with dump_only fields and we came to the conclusion that from client perspective, those should be treated just as unknown fields (see https://github.com/marshmallow-code/marshmallow/issues/875).
最重要的是,您的PUT有效负载不应包含dump_only字段.或者,您可以将EXCLUDE策略设置为您的架构,但是我更喜欢前一个选项.
Bottom line, your PUT payload should not include dump_only fields. Or you could set the EXCLUDE policy to your schema, but I'd favor the former option.
这篇关于SQLAlchemy @property使用dump_only在棉花糖中导致“未知字段"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!