Python 在peewee union select中放置一个空字段
我尝试选择两个具有公共字段的表。在原始MySQL查询中,我可以这样写:Python 在peewee union select中放置一个空字段,python,mysql,peewee,Python,Mysql,Peewee,我尝试选择两个具有公共字段的表。在原始MySQL查询中,我可以这样写: SELECT t1.id, t1.username, t1.date FROM table1 as 't1' UNION SELECT t2.id, "const_txt", t2.date FROM table2 as 't2' 在该查询中,username字段不在表2中,我设置了const_txt 所以,在peewee中,我想合并两个具有相同上述情况的表 class PeeweeBaseModel(Model):
SELECT t1.id, t1.username, t1.date FROM table1 as 't1' UNION SELECT t2.id, "const_txt", t2.date FROM table2 as 't2'
在该查询中,username
字段不在表2中,我设置了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()
但是常量文本
不被字段接受,并且在结果查询中被忽略
问题是:如何定义表中不存在的字段并在查询中手动设置
(我不喜欢使用SQL()函数。)
谢谢 您可以在SELECT语句中使用SQL()
u = (
Table1(
Table1.id,
Table1.username,
Table1.date
).select()
|
Table2(
Table2.id,
SQL(" '' AS username "),
Table2.date
).select()
).select().execute()
这很好。。。但正如我前面所说的,我想要另一种方法,除了SQL()。但再次感谢您。这正是
SQL
函数的作用。@Reza-S4,只是想澄清一下,您希望看到什么类型的API而不是SQL
?如果我不清楚,我不明白您为什么不想使用SQL()
。有什么原因吗?@coleifer,我认为@Reza-S4需要其他方法来解决这个问题,但我认为使用SQL()
是解决这个问题的唯一方法