Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
protibimbok opened this issue Feb 4, 2024 · 3 comments
Open

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

protibimbok opened this issue Feb 4, 2024 · 3 comments

Comments

@protibimbok
Copy link

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
Copy link

gmgs-999 commented Mar 5, 2024

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
Copy link
Author

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

@gmgs-999
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants