How to access different parameter from field.Method in Python

40 views Asked by At

I would like to change my postal code to '' if its None but cannot access the country_code parameter properly to do it. What am I doing wrong?

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)

2

There are 2 answers

0
Dionysus On

The problem was that I tried to access postal as an object and not as a dictionary so the solution is

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)
1
Tobin On

There are several problems in your code: the variable you pass as a parameter to your function is not the one used, then the variable allowed_countries is not correctly declared.

In addition, you use two different variables: the declared variable countryCode uses the CamelCase style while the variable you call uses the lower_case_with_underscores style: country_code. You must harmonize the names of your variables:

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)