如果我的邮政编码是None
,我想将其更改为''
,但无法正确访问country_code参数。我做错了什么?
class AddressSchema(Schema):
def _postal_check(self, postal):
allowed_countries = ["GE","BT","HK","MO"]
postal_code = postal.postalCode
country_code = postal.countryCode
if postal_code is None and country_code in allowed_countries:
postal_code = ''
return postal_code
countryCode = fields.Str(validate=Length(equal=2), required=True)
postalCode = fields.Method(serialize='_postal_check', allow_none=True, required=True)
代码中存在以下几个问题:作为函数参数传递的变量不是所使用的变量,那么变量allowed_countries
没有正确声明。
此外,您使用两个不同的变量:声明的变量countryCode
使用CamelCase
样式,而您调用的变量使用lower_case_with_underscores style
:country_code
。您必须协调变量的名称:
class AddressSchema(Schema):
def _postal_check(self, postal):
allowed_countries = ["GE","BT","HK","MO"]
if postal is None and self.country_code in allowed_countries:
self.postal_code = ''
return self.postal_code
country_code = fields.Str(validate=Length(equal=2), required=True)
postal_code = fields.Method(serialize='_postal_check', allow_none=True, required=True)
问题是我试图将postal作为对象而不是字典访问,所以解决方案是
class AddressSchema(Schema):
def _postal_check(self, postal):
allowed_countries = ["GE","BT","HK","MO"]
postal_code = postal['postalCode']
country_code = postal['countryCode']
if postal_code is None and country_code in allowed_countries:
postal_code = ''
return postal_code
country_code = fields.Str(validate=Length(equal=2), required=True)
postal_code = fields.Method(serialize='_postal_check', allow_none=True, required=True)