In Django, I know using filter
with multiple arguments gets translated into SQL AND
clauses. From the Django Book:
You can pass multiple arguments into filter() to narrow down things further:
>>> Publisher.objects.filter(country="U.S.A.", state_province="CA") [<Publisher: Apress>]
Those multiple arguments get translated into SQL AND clauses. Thus, the example in the code snippet translates into the following:
SELECT id, name, address, city, state_province, country, website FROM books_publisher WHERE country = 'U.S.A.' AND state_province = 'CA';
How do I create a Django queryset that gets translated into SQL OR
clauses? For example:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE state_province = 'AZ'
OR state_province = 'CA';
The raw() manager method can be used to perform raw SQL queries that return model instances: Manager. raw (raw_query, params=(), translations=None) This method takes a raw SQL query, executes it, and returns a django.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
Django officially supports five database management systems: PostgreSQL, MariaDB, MySQL, Oracle, and SQLite (Django, 2020). Some third parties provide backends for other DBMSs, such as CockroachDB, Firebird, and Microsoft SQL Server.
using the Q operator available in django.db.models
IE:
from django.db.models import Q
Publisher.objects.filter(Q(state_province="CA") | Q(state_province="AZ"))
Have a look in the docs here: http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With