0% found this document useful (0 votes)
1K views29 pages

Django ORM and Queryset

Django Queryset allows you to write queries against Django models and databases using Python code rather than raw SQL. A queryset represents a collection of objects from a model. Querysets provide methods to filter, order, annotate, and paginate the results efficiently at the database level. Common queryset methods return another queryset, like filter(), exclude(), order_by(). Others return values rather than a queryset, like get(), count(), aggregate(). Querysets can be used to perform CRUD operations and translate directly to SQL queries against the database.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views29 pages

Django ORM and Queryset

Django Queryset allows you to write queries against Django models and databases using Python code rather than raw SQL. A queryset represents a collection of objects from a model. Querysets provide methods to filter, order, annotate, and paginate the results efficiently at the database level. Common queryset methods return another queryset, like filter(), exclude(), order_by(). Others return values rather than a queryset, like get(), count(), aggregate(). Querysets can be used to perform CRUD operations and translate directly to SQL queries against the database.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Django ORM

And
Queryset
Django Queryset and its built-in ORM (Object
Relational Mapper). Once you master Django
Queryset, you can write one universal query for any
database engine connected.

What Is Django Queryset?

A queryset is simply a list of objects from the


Django Models. When using the Django ORM
creating a new row in the table is simply like
creating a new object of Model class. Django ORM
maps these Model objects to Relational database
query.

Any SQL query can be written easily as Django


queryset. You can separately test the query
for Create, Filter, Update, Order, etc. in Django
Shell or in the views.py.
The syntax for a queryset is always like:

ModelName.objects.method_name(arguments)

For example, to get all data from the


model Blog under app named myapp, start a Python
shell and run the following:

python manage.py shell

>>> from myapp.models import Blog


>>> queryset = Blog.objects.all()
QuerySet [...]
Methods In Queryset API

There are several methods under the Django


Queryset API. Some methods return another
queryset object and thus can be followed by another
methods.
queryset_object  = Model.objects.all().filter()

These queryset objects needs to be accessed


iteratively in the template pages with the following
syntax:

{ % for i in queryset_object % }
{ {i.fieldname} }
...
{ % endfor % }

On the other hand, some queryset methods do not


return a new queryset or simply return data items.
For example:
ueryset_object  = Model.objects.get(id=1)

The result of a get query can be accessed in the


template pages without using any loop, or simply
with the below syntax.

{ {queryset_object.fieldname} }

Django Queryset Methods That Return Another


Queryset

 filter()
 exclude()
 annotate()
 alias()
 order_by()
 reverse()
 distinct()
 values()
 values_list()
 dates()
 datetimes()
 none()
 all()
 union()
 intersection()
 difference()
 select_related()
 prefetch_related()
 extra()
 defer()
 only()
 using()
 select_for_update()
 raw()

Django Queryset Methods That Do Not Return


Another Queryset

 get()
 create()
 get_or_create()
 update_or_create()
 bulk_create()
 bulk_update()
 count()
 in_bulk()
 iterator()
 latest()
 earliest()
 first()
 last()
 aggregate()
 exists()
 contains()
 update()
 delete()
 as_manager()
 explain()

SQL Query Vs Django ORM


Queryset

SQL Query Django ORM Queryset


select * from table; Model.objects.all()
select * from table where Model.objects.filter(fieldname=v
fieldname=value; alue)
select distinct Model.objects.distinct(column_n
column_names from ames)
table;
insert into table(field1, Model.objects.create(field1=valu
field2, …) values (value1, e1, field2=value2, …)
value2, …);
update table set Model.objects.filter(condition).up
column_name = value date( column_name=value)
where condition;
delete from table where Model.objects.filter(condition).de
condition lete()
select columns from table Model.objects.filter(condition).or
order_by column asc| der_by (column_for_asc, -
desc; column_for_desc)
select columns from table Model.objects.filter(condition1,
where conditon1 and condition2)
condition2
select columns from table Model.objects.filter(condition1) |
where conditon1 or Model.objects.filter(condition2)
condition2
select columns from table Model.obejcts.exclude(condition)
where not condition
select max(column) from Model.obejects.filter(column).ma
table; x()
select min(column) from Model.obejects.filter(column).mi
table; n()
select avg(column) from Model.obejects.filter(column).av
table; g()
select sum(column) from Model.obejects.filter(column).su
table; m()
select count(column) Model.obejects.filter(column).co
from table; unt()

CRUD Queryset Example Using


Todo App
Models.Py
from django.db import models

class Todo(models.Model):
title = models.CharField(max_length=120,
unique=True)
description = models.TextField(blank=True)
status = models.BooleanField(default=False)
def __str__(self):
return self.title

Views.Py
from django.shortcuts import render, redirect
from .models import Todo

def add_task(request):
if request.method=="POST":
title = request.POST['title']
q = Todo.objects.create(title=title)
q.save()
return redirect('/')
return render(request, 'add_task.html', {})

def tasks(request):
q = Todo.objects.all()
return render(request, 'tasks.html',
{'tasks':q})
def update(request, id):
selected_task = Todo.objects.get(id=id)
if request.method=="POST":
form = TodoForm(request.POST,
instance=selected_task)
if form.is_valid():
form.save()
return redirect('/tasks/')
else:
form = TodoForm(instance=selected_task)
return render(request, 'update_task.html',
{'form':form})

def delete(request, id):


task = Todo.objects.get(id=id)
task.delete()
return redirect('/tasks/')

Search Field

Index.Html
<form>
<input type="text" name="search"
autocomplete="off" required>
<input type="submit" value="Search">
</form>

Views.Py
def search_function(request):
search = request.GET.get('search')
q = Model.objects.filter(fieldname=search)
return render(request, 'index.html', {'q':q})

Let us consider a simple base model for a


person with attributes name, age, and
gender.

To implement the above entity, we would


model it as a table in SQL.
CREATE TABLE Person (
id int,
name varchar(50),
age int NOT NULL,
gender varchar(10),
);
The same table is modeled in Django as a
class which inherits from the base Model
class. The ORM creates the equivalent
table under the hood.
class Person(models.Model):
name =
models.CharField(max_length=50,
blank=True)
age = models.IntegerField()
gender =
models.CharField(max_length=10,
blank=True)
The most used data types are:
SQL Django

INT IntegerField()

VARCHAR(n) CharField(max_length=n)

TEXT TextField()
SQL Django

FLOAT(n) FloatField()

DATE DateField()

TIME TimeField()

DATETIME DateTimeField()

The various queries we can use are:

SELECT Statement
Fetch all rows
SQL:
SELECT *
FROM Person;
Django:
persons = Person.objects.all()
for person in persons:
print(person.name)
print(person.gender)
print(person.age)
Fetch specific columns
SQL:
SELECT name, age
FROM Person;
Django:
Person.objects.only('name', 'age')
Fetch distinct rows
SQL:
SELECT DISTINCT name, age
FROM Person;
Django:
Person.objects.values('name',
'age').distinct()
Fetch specific number of rows
SQL:
SELECT *
FROM Person
LIMIT 10;
Django:
Person.objects.all()[:10]
LIMIT AND OFFSET keywords
SQL:
SELECT *
FROM Person
OFFSET 5
LIMIT 5;
Django:
Person.objects.all()[5:10]

WHERE Clause
Filter by single column
SQL:
SELECT *
FROM Person
WHERE id = 1;
Django:
Person.objects.filter(id=1)
Filter by comparison operators
SQL:
WHERE age > 18;
WHERE age >= 18;
WHERE age < 18;
WHERE age <= 18;
WHERE age != 18;
Django:
Person.objects.filter(age__gt=18)
Person.objects.filter(age__gte=18)
Person.objects.filter(age__lt=18)
Person.objects.filter(age__lte=18)
Person.objects.exclude(age=18)
BETWEEN Clause
SQL:
SELECT *
FROM Person
WHERE age BETWEEN 10 AND 20;
Django:
Person.objects.filter(age__range=(1
0, 20))
LIKE operator
SQL:
WHERE name like '%A%';
WHERE name like binary '%A%';
WHERE name like 'A%';
WHERE name like binary 'A%';
WHERE name like '%A';
WHERE name like binary '%A';
Django:
Person.objects.filter(name__icontai
ns='A')
Person.objects.filter(name__contain
s='A')
Person.objects.filter(name__istarts
with='A')
Person.objects.filter(name__startsw
ith='A')
Person.objects.filter(name__iendswi
th='A')
Person.objects.filter(name__endswit
h='A')
IN operator
SQL:
WHERE id in (1, 2);
Django:
Person.objects.filter(id__in=[1,
2])

AND, OR and NOT


Operators
SQL:
WHERE gender='male' AND age > 25;
Django:
Person.objects.filter(gender='male'
, age__gt=25)
SQL:
WHERE gender='male' OR age > 25;
Django:
from django.db.models import Q
Person.objects.filter(Q(gender='mal
e') | Q(age__gt=25))
SQL:
WHERE NOT gender='male';
Django:
Person.objects.exclude(gender='male
')

NULL Values
SQL:
WHERE age is NULL;
WHERE age is NOT NULL;
Django:
Person.objects.filter(age__isnull=T
rue)
Person.objects.filter(age__isnull=F
alse)

# Alternate approach
Person.objects.filter(age=None)
Person.objects.exclude(age=None)

ORDER BY Keyword
Ascending Order
SQL:
SELECT *
FROM Person
order by age;
Django:
Person.objects.order_by('age')
Descending Order
SQL:
SELECT *
FROM Person
ORDER BY age DESC;
Django:
Person.objects.order_by('-age')

INSERT INTO Statement


SQL:
INSERT INTO Person
VALUES ('Jack', '23', 'male');
Django:
Person.objects.create(name='jack',
age=23, gender='male)

UPDATE Statement
Update single row
SQL:
UPDATE Person
SET age = 20
WHERE id = 1;
Django:
person = Person.objects.get(id=1)
person.age = 20
person.save()
Update multiple rows
SQL:
UPDATE Person
SET age = age * 1.5;
Django:
from django.db.models import F

Person.objects.update(age=F('age')*
1.5)
DELETE Statement
Delete all rows
SQL:
DELETE FROM Person;
Django:
Person.objects.all().delete()
Delete specific rows
SQL:
DELETE FROM Person
WHERE age < 10;
Django:
Person.objects.filter(age__lt=10).d
elete()

Aggregation
MIN Function
SQL:
SELECT MIN(age)
FROM Person;
Django:
>>> from django.db.models import
Min
>>>
Person.objects.all().aggregate(Min(
'age'))
{'age__min': 0}
MAX Function
SQL:
SELECT MAX(age)
FROM Person;
Django:
>>> from django.db.models import
Max
>>>
Person.objects.all().aggregate(Max(
'age'))
{'age__max': 100}
AVG Function
SQL:
SELECT AVG(age)
FROM Person;
Django:
>>> from django.db.models import
Avg
>>>
Person.objects.all().aggregate(Avg(
'age'))
{'age__avg': 50}
SUM Function
SQL:
SELECT SUM(age)
FROM Person;
Django:
>>> from django.db.models import
Sum
>>>
Person.objects.all().aggregate(Sum(
'age'))
{'age__sum': 5050}
COUNT Function
SQL:
SELECT COUNT(*)
FROM Person;
Django:
Person.objects.count()

GROUP BY Statement
Count of Person by gender
SQL:
SELECT gender, COUNT(*) as count
FROM Person
GROUP BY gender;
Django:
Person.objects.values('gender').ann
otate(count=Count('gender'))

HAVING Clause
Count of Person by gender if number
of person is greater than 1
SQL:
SELECT gender, COUNT('gender') as
count
FROM Person
GROUP BY gender
HAVING count > 1;
Django:
Person.objects.annotate(count=Count
('gender'))
.values('gender', 'count')
.filter(count__gt=1)
JOINS
Consider a foreign key relationship
between books and publisher.
class Publisher(models.Model):
name =
models.CharField(max_length=100)

class Book(models.Model):
publisher =
models.ForeignKey(Publisher,
on_delete=models.CASCADE)
Fetch publisher name for a book
SQL:
SELECT name
FROM Book
LEFT JOIN Publisher
ON Book.publisher_id = Publisher.id
WHERE Book.id=1;
Django:
book =
Book.objects.select_related('publis
her').get(id=1)
book.publisher.name
Fetch books which have specific
publisher
SQL:
SELECT *
FROM Book
WHERE Book.publisher_id = 1;
Django:
publisher =
Publisher.objects.prefetch_related(
'book_set').get(id=1)
books = publisher.book_set.all()

You might also like