我可能误解了您的问题,但在我看来,用户是新用户还是现有用户,是架构外部的状态(因为架构是无状态的),因此需要将其传递给验证器. 在与您类似的情况下,我做了这样的事情:
from marshmallow import fields, validates_schema, Schema
from marshmallow.validate import OneOf
from marshmallow.exceptions import ValidationError
class Foo(Schema):
country = fields.String(validate=OneOf(('A', 'B')), missing=None)
# Some sort of hint that indicates if it's a new
# user or not. Could be record creation date, etc.
new_user = fields.Boolean(missing=False)
@validates_schema
def check_country(self, instance):
if instance['new_user'] and instance['country'] is None:
raise ValidationError("count can not be none")
观察:
schema = Foo()
schema.load({})
>>> UnmarshalResult(data={'new_user': False, 'country': None}, errors={})
schema.load({'new_user':True})
>>> UnmarshalResult(data={'new_user': True, 'country': None}, errors={'_schema': ['count can not be none']})
schema.load({'new_user':True, 'country': 'A'})
>>> UnmarshalResult(data={'new_user': True, 'country': 'A'}, errors={})
schema.load({'new_user':False})
>>> UnmarshalResult(data={'new_user': False, 'country': None}, errors={})