In this blog, we will learn the most commonly used Django QuerySet examples with their equivalent SQL code.
A QuerySet is a collection of objects/rows fetched from your database. The QuerySet can be constructed, filtered, sliced, and passed around without actually hitting the database. More about QuerySet you can find Django’s official website.
Getting Started
Note: All code examples below are written and tested with the Django 4.1 and PostgreSQL 15 versions. And many of them will work on lower/higher versions of Django and for other relational database engines without any errors.
Below is the ER-Model for models we will use to execute queries. There are many fields in these tables but we will only use some of them.
class Film(models.Model):
film_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
release_year = models.IntegerField(blank=True, null=True)
language = models.ForeignKey('Language', models.DO_NOTHING)
rental_duration = models.SmallIntegerField()
rental_rate = models.DecimalField(max_digits=4, decimal_places=2)
length = models.SmallIntegerField(blank=True, null=True)
replacement_cost = models.DecimalField(max_digits=5, decimal_places=2)
rating = models.TextField(blank=True, null=True)
last_update = models.DateTimeField()
special_features = models.TextField(blank=True, null=True)
fulltext = models.TextField()
class Meta:
db_table = 'film'
class Language(models.Model):
language_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
last_update = models.DateTimeField()
class Meta:
db_table = 'language'
Contents
SELECT – Query data from a single table
ORDER BY – Sort result set returned from a query
SELECT DISTINCT – Removes duplicate rows from the result set
WHERE – Filter rows based on a specified condition
LIMIT – Get a subset of rows generated by a query
INNER JOIN – fetch rows from one table that has the corresponding rows in other tables
INSERT – Insert a single row into a table
UPDATE – update existing data in a table
DELETE – delete data in a table
1. SELECT – Query data from a single table
The SELECT is the most common task when you work with the database to query data from tables. Below are some SELECT statements with their equivalent Django QuerySet.
2. ORDER BY – Sort result set returned from a query
When you query data using the SELECT statement, it returns rows in an unspecified order. To sort the result set rows, you use the ORDER BY clause in the SELECT statement. In Django QuerySet it can be done by the order_by(column_name) function.
i. Sort rows by one column in ASCENDING order
SQL Code
SELECT * FROM film ORDER BY title ASC;
Django QuerySet
Film.objects.all().order_by('title')
ii. Sort rows by one column in DESCENDING order
SQL Code
SELECT * FROM film ORDER BY title DESC;
Django QuerySet
Film.objects.all().order_by('-title')
iii. Sort rows by multiple columns in ASCENDING order
3. SELECT DISTINCT – Removes duplicate rows from the result set
In the SELECT statement, the DISTINCT clause removes duplicate rows from a result set. In Django QuerySet distinct() method is used to remove duplicates.
i. Show unique data from a single column from the table.
SQL Code
SELECT DISTINCT rating FROM film;
Django QuerySet
Film.objects.values('rating').distinct()
ii. Show unique data from multiple columns from the table.
SQL Code
SELECT DISTINCT rating, title FROM film;
Django QuerySet
Film.objects.values('rating', 'title').distinct()
4. WHERE – Filter rows based on a specified condition
The SELECT statement returns all rows from one or more columns from a table. To select rows that satisfy a given condition, you have to use a WHERE clause.
i. Using WHERE clause with the equal (=) operator
SQL Code
SELECT * FROM film WHERE title='Aladdin Calendar';
Django QuerySet
Film.objects.filter(title='Aladdin Calendar')
ii. Using the WHERE clause with the AND operator
SQL Code
SELECT * FROM film WHERE (title='Aladdin Calendar' AND rating='NC-17');
v. Using WHERE clause with the LIKE operator to match BEGINNING characters
SQL Code
SELECT * FROM film WHERE title LIKE 'Ala%';
Django QuerySet
Film.objects.filter(title__startswith='Ala')
vi. Using WHERE clause with the LIKE operator to match ENDING characters
SQL Code
SELECT * FROM film WHERE title LIKE '%ape';
Django QuerySet
Film.objects.filter(title__endswith='ape')
vii. Using WHERE clause with the LIKE operator to match characters from ANYWHERE
SQL Code
SELECT * FROM film WHERE title LIKE '%sag%';
Django QuerySet
Film.objects.filter(title__contains='sag')
Note: These commands also support case-insensitive lookups. Check startswith, istartswith, endswith, iendswith, contains, icontains in the official docs for the details.
viii. Using the WHERE clause with the BETWEEN operator
SQL Code
SELECT * FROM film WHERE length BETWEEN 100 AND 110;
Django QuerySet
Film.objects.filter(length__range=[100, 110])
viii. Using the WHERE clause with the NOT EQUAL operator
SQL Code
SELECT * FROM film WHERE rating <> 'PG';
Django QuerySet
Film.objects.filter(~Q(rating='PG'))
ix. Using the WHERE clause with the LESS THAN operator
SQL Code
SELECT * FROM film WHERE length < 100;
Django QuerySet
Film.objects.filter(length__lt=100)
x. Using the WHERE clause with the LESS THAN OR EQUAL operator
SQL Code
SELECT * FROM film WHERE length <= 100;
Django QuerySet
Film.objects.filter(length__lte=100)
xi. Using the WHERE clause with the GREATER THAN operator
SQL Code
SELECT * FROM film WHERE length > 100;
Django QuerySet
Film.objects.filter(length__gt=100)
xii. Using the WHERE clause with the GREATER THAN OR EQUAL operator
SQL Code
SELECT * FROM film WHERE length >= 100;
Django QuerySet
Film.objects.filter(length__gte=100)
xiii. Using the WHERE clause with the IS NULL operator
SQL Code
SELECT * FROM film WHERE title IS NULL;
Django QuerySet
Film.objects.filter(title__isnull=True)
5. LIMIT – Get a subset of rows generated by a query
The LIMIT is an optional clause of the SELECT statement that constrains the number of rows returned by the query. In Django, we can use array slicing to limit the number of rows returned.
SQL Code
SELECT * FROM film LIMIT 10;
Django QuerySet
Film.objects.all()[:10]
6. INNER JOIN – fetch rows from one table that has the corresponding rows in other tables
Join is used to combine columns from one or more tables based on the values of the common columns between related tables. The common columns are typically the primary key columns of the first table and the foreign key columns of the second table.
The following statement joins the first table Film with the second table Language by matching the values in the Film.language_id and Language.language_id columns:
i. Select all columns from both tables
SQL Code
SELECT * FROM film INNER JOIN language ON film.language_id=language.language_id;
Django QuerySet
Film.objects.select_related('language')
ii. Select specific columns from both tables
SQL Code
SELECT film.title, language.name FROM film INNER JOIN language ON film.language_id=language.language_id;
Suppose you’ve saved a single row in the lang_obj object. You can update it by assigning a new value to a specific field and then calling save() command.
Django QuerySet
lang_obj.name = 'Hindi' lang_obj.save()
9. DELETE – delete data from a table
Suppose you’ve fetched a single row in the lang_obj object. You can delete it by calling the delete() command.