0

我想将我的邮政编码更改为 ''如果它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)

4

2 回答 2

0

问题是我试图将邮政作为一个对象而不是作为字典来访问,所以解决方案是

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)
于 2020-12-02T18:22:56.610 回答
0

您的代码中有几个问题:您作为参数传递给函数的变量不是使用的变量,那么该变量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)
于 2020-12-02T16:43:29.227 回答