根据数据覆盖字段模式-棉花糖 [英] Override field schema based on data - Marshmallow
问题描述
我刚开始使用棉花糖,所以如果有解决问题的更优雅的方法,请告诉我.字段会根据用户类型(学生/工作人员)而有所不同
I'm just getting started with marshmallow so if there's a more elegant way to solve the issue please let me know. Fields will be varied based on the user type (student/staff)
{
"type": "student",
"name": "Student 1",
"class": "V Std",
"section": "A Class"
}
如果输入 Staff
,我们需要验证 designation
和 experience
跳过 class
和 section 代码>
if type Staff
we need to validate designation
and experience
skip class
and section
{
"type": "staff",
"name": "Staff 1",
"designation": "Professor",
"experience": "2 Year"
}
我有以下简单的模型和架构.
I have the following simple model and schema.
class AddUser(Resource):
def post(self):
content = request.get_json(silent=True)
try:
data = UserSchema().load(content)
print(data)
except ValidationError as err:
return err.messages, 400
class UserSchema(Schema):
type = fields.Str(required=True,validate=OneOf(['student', 'staff'], error='Invalid User Type'), error_messages={'required': 'User type required'})
name = fields.Str(required=True)
class = fields.Str()
section = fields.Str()
designation = fields.Str()
experience = fields.Str()
@post_load
# @pre_load
# @validates_schema
def unwrap_envelope(self, data):
student = {
class: fields.Str(required=True),
section: fields.Str(required=True)
}
staff = {
designation: fields.Str(required=True),
experience: fields.Str(required=True)
}
# Fields are getting updated but it is **not raising the error**
if data['type'] == 'student':
self.declared_fields.update(student)
elseif data['type'] == 'staff':
self.declared_fields.update(staff)
return data
推荐答案
我认为您正在寻找的是多态性.
I think what you're looking for is polymorphism.
要实现这一目标并非易事,而且棉花糖还没有一种简便的方法来实现.您可以检查 marshmallow-oneofschema 和
It's not straightforward to achieve and marshmallow does not come with an easy way to do it. You can check marshmallow-oneofschema and marshmallow-polyfield. Those two third-party libraries are meant for that. They both have their pros and cons, so none of them was included in marshmallow core.
这篇关于根据数据覆盖字段模式-棉花糖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!