【问题标题】:Union over fields having different names using peewee使用peewee联合具有不同名称的字段
【发布时间】:2016-05-23 20:41:08
【问题描述】:
我使用peewee 作为 ORM 并且有两个这样的类:
class A(Model):
name = CharField()
body = TextField()
class B(Model):
title = CharField()
body = TextField()
我想获取来自A 和B 的所有条目,它们的title/name 以'abc' 等一些字符开头。根据文档,| 运算符应该会有所帮助,但我什至无法执行生成的Expression。显然我想在幕后有一个UNION 和AS 表达式。我如何通过 peewee 获得这个?
【问题讨论】:
标签:
python
sql
orm
peewee
【解决方案1】:
你应该能够得到你想要的结果
result = (
A().select(A.name.alias('name_title'), A.body).where(A.name == 'abc') |
B().select(B.title.alias('name_title'), B.body).where(B.title == 'abc')
).select().execute()
或
search_text = 'abc'
table_a_results = A().select(
A.name.alias('name_title'),
A.body
).where(A.name == search_text)
table_b_results = B().select(
B.name.alias('name_title'),
B.body
).where(B.title == search_text)
result = ( table_a_results | table_b_results ).select().execute()
.alias() 方法根据docs 为您提供AS 功能