Union over fields having different names using peewee
Asked Answered
P

1

8

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?

Pistareen answered 23/5, 2016 at 20:41 Comment(0)
L
4

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

Levant answered 27/5, 2016 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.