Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union over fields having different names using peewee

I'm using peewee as ORM and have two classes like this:

class A(Model):
    name = CharField()
    body = TextField()

class B(Model):
    title = CharField()
    body = TextField()

I would like to get all entries from A and B whose title/name start with some characters like 'abc'. According to the documentation the | operator should help, but I'm not even able to execute the resulting Expression. Obviously I would like to have a UNION and AS expression behind the scenes. How do I get this via peewee?

like image 207
Achim Avatar asked May 23 '16 20:05

Achim


1 Answers

You should be able to get the result you want with something like

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()

or

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()

The .alias() method to gets you the AS functionality as per the docs

like image 133
KMR Avatar answered Nov 15 '22 06:11

KMR