在 peewee union select 中放置一个空字段

Put an empty field in peewee union select

我正在尝试 select 两个具有共同领域的 table。在原始 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 字段不在 table2 中,我改为设置 const_txt

所以,在 peewee 中,我想联合两个具有相同上述情况的 table。

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 不被字段接受,在结果查询中忽略。

问题是:如何定义我的 table 中不存在的字段并在查询中手动设置它?

(而且我不喜欢使用 SQL() 函数。)

谢谢。

您可以在 SELECT 语句中使用 SQL()。

u = (
    Table1(
        Table1.id,
        Table1.username,
        Table1.date
    ).select() 
    | 
    Table2(
        Table2.id,
        SQL(" '' AS username "),
        Table2.date
    ).select()
).select().execute()