pythonsqlalchemyflask-sqlalchemywebargs

is it possible to store a PhoneNumberType from SQLalchemy as null?


I'm creating an API with webargs and python, and I have a condition that a user must supply either a phone number or email address. If the user provides an email address only, then when sqlalchemy tries to instantiate a PhoneNumberType, I get the expected error:

sqlalchemy_utils.types.phone_number.PhoneNumberParseException: (1) (1) The phone number supplied was None.

my question is how can i make this database field able to accept a null phone number and just keep that entry null?

Here is part of my user model:

import flask_sqlalchemy as sa
...
phone         = db.Column(db.Unicode(20), nullable=True)
country_code  = db.Column(db.Unicode(8), nullable=False)
_phone        = sa.orm.composite(PhoneNumber, phone, country_code)

country code is needed for other reason, but is there a way to make say... _Phone null ??


Solution

  • No, because the library depends on a google lib that must take a raw_number argument. you can do a try/except and ignore a

    phonenumbers.phonenumberutil.NumberParseException
    

    When the field is null, the object won't instantiate even if you manually change the entry.