Reza-S4
Reza-S4

Reputation: 1052

Put an empty field in peewee union select

I'm try to select two table that have some common field. in raw MySQL query, i can write this:

SELECT t1.id, t1.username, t1.date FROM table1 as 't1' UNION SELECT t2.id, "const_txt", t2.date FROM table2  as 't2'

In that query ,the username field is not in table2 and I set const_txt instead.

So, in peewee, i want to union two table that have the same above situation.

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 ...

and then , union two model. something like this:

u = (
    Table1(
        Table1.id,
        Table1.username,
        Table1.date
    ).select() 
    | 
    Table2(
        Table2.id,
        "const_text_instead_real_field_value",
        Table2.date
    ).select()
).select().execute()

But the const_text is not accepted by a field and ignore in result query.

the question is: How can I define a field that does not exist in my table and set it manually in query?

(And I prefer not using SQL() function.)

thanks.

Upvotes: 4

Views: 789

Answers (1)

Zaaferani
Zaaferani

Reputation: 951

you can use SQL() in SELECT statement.

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

Upvotes: 4

Related Questions