是否可以将 SQLalchemy 中的 PhoneNumberType 存储为 null?

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

我正在创建一个带有 webargs 和 python 的 API,并且我有一个条件,即用户必须提供 phone 号码或电子邮件地址。如果用户仅提供电子邮件地址,则当 sqlalchemy 尝试实例化 PhoneNumberType 时,我会收到预期的错误:

sqlalchemy_utils.types.phone_number.PhoneNumberParseException: (1) (1) 提供的 phone 号码是 None.

我的问题是如何让这个数据库字段能够接受一个空 phone 数字并保持该条目为空?

这是我的用户模型的一部分:

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)

出于其他原因需要国家代码,但有没有办法让..._Phone 为空??

不,因为该库依赖于一个必须采用 raw_number 参数的 google 库。你可以做 try/except 而忽略

phonenumbers.phonenumberutil.NumberParseException

当字段为空时,即使您手动更改条目,对象也不会实例化。