【发布时间】:2015-02-15 22:56:55
【问题描述】:
我正在查询第一个非空用户名:
query = session.query(
Account.id.label('acc_id'),
Account.username.label('acc_username'),
User.username.label('us_username'),
User.another_username.label('also_username'),
User.email.label('email')
).join(Account.user)
然后我在acc_username、us_username、also_username 和email 中搜索第一个非空值。为了做到这一点,我准备了一个函数来创建一个 KeyedTuple 从找到的 id 和第一个非空字符串值:
for q in query.all():
account_tuple = KeyedTuple(
[q.acc_id, q.acc_username or q.us_username or q.also_username or q.email or ''],
labels=_LABELS)
但我宁愿使用某种形式的 coalesce,除了返回第一个非空值(在 Python 中首先是 not False 值)而不是 not NULL。有没有正确的方法来做到这一点?我非常感谢将所有这些逻辑保留在查询中,而不是在单独的函数中创建另一个 KeyedTuple。
【问题讨论】:
标签: python sqlalchemy coalesce