Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Django queryset equivalent to a SQL query using the OR operator?

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'; 
like image 871
saltycrane Avatar asked May 05 '09 23:05

saltycrane


People also ask

What is the command to generate the SQL equivalent to Django model?

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.

What is QuerySet in Django with example?

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.

Can we use SQL with Django?

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.


1 Answers

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

like image 113
Mike Scott Avatar answered Sep 17 '22 18:09

Mike Scott