在peewee union select中放置一个空字段
作者:互联网
我尝试选择两个具有某些公共字段的表.在原始MySQL查询中,我可以这样写:
SELECT t1.id, t1.username, t1.date FROM table1 as 't1' UNION SELECT t2.id, "const_txt", t2.date FROM table2 as 't2'
在该查询中,用户名字段不在table2中,而是设置了const_txt.
因此,在peewee中,我要合并具有相同上述情况的两个表.
class PeeweeBaseModel(Model):
class Meta:
database = my_db
class Table1(PeeweeBaseModel):
id = PrimaryKeyField()
username = CharField(255)
date = DateTimeField()
#other fields ...
class Table2(PeeweeBaseModel):
id = PrimaryKeyField()
date = DateTimeField()
#other fields ...
然后,合并两个模型.像这样的东西:
u = (
Table1(
Table1.id,
Table1.username,
Table1.date
).select()
|
Table2(
Table2.id,
"const_text_instead_real_field_value",
Table2.date
).select()
).select().execute()
但是const_text不会被字段接受,并在结果查询中忽略.
问题是:如何定义表中不存在的字段并在查询中手动设置它?
(而且我更喜欢不使用SQL()函数.)
谢谢.
解决方法:
您可以在SELECT语句中使用SQL().
u = (
Table1(
Table1.id,
Table1.username,
Table1.date
).select()
|
Table2(
Table2.id,
SQL(" '' AS username "),
Table2.date
).select()
).select().execute()
标签:peewee,python,mysql 来源: https://codeday.me/bug/20191120/2044444.html