首页 > 解决方案 > 如何在 Python 中从 field.Method 访问不同的参数

问题描述

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

标签: pythonflaskmarshmallowflask-marshmallow

解决方案


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

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)

推荐阅读