ponyorm / pony

Pony Object Relational Mapper
Apache License 2.0
3.63k stars 245 forks source link

How to combine two `query.filter()` calls using `OR` operator? #701

Open protibimbok opened 8 months ago

protibimbok commented 8 months ago

This is really basic, but I could not find it anywhere.

query = select(b for b in BookModel)
f1 = lambda b: b.id == 1
f2 = lambda b: b.id == 2
query = query.filter(f1)
query = query.filter(f2)
print(query.get_sql())

This one prints:

SELECT `b`.`id`, `b`.`title`, `b`.`author`, `b`.`genre`, `b`.`price`
FROM `books` `b`
WHERE `b`.`id` = 1
AND `b`.`id` = 2

How can I make it so that it executes:


WHERE `b`.`id` = 1
OR `b`.`id` = 2
``
gmgs-999 commented 7 months ago

Try this!:


with pny.db_session():
     query = pny.select(b for b in Model)
     query = query.filter(lambda b: b.id ==1 or b.id == 2)
     print(query.get_sql())```

### output
SELECT "b"."id"
FROM "Model" "b"
WHERE ("b"."id" = 1 OR "b"."id" = 2)`
protibimbok commented 6 months ago

There is a reason I wrote the filters as two different lambdas. It's because it'll be generated dynamically.

gmgs-999 commented 6 months ago

Yes, but I think that Pony transform two consecutives filters into an AND in SQL it's logic. It's like you make first a Substet of data an then you make a subset of the original substet (and that transform it in an AND in the sql query). For me that it's logic and if you try it in others python ORM's (like sqlalchemy) you will have the same result. Cheers!