Django ORM — Examples and Practice Problems (2024)

Welcome to Django ORM practice. This article will provide you problems and solutions based on dataset to help you practice Django ORM and take you from beginner to professional in making queries using Django ORM. You can see Django Documentation for getting familiar with how to make models and queries using Django, then use this article as means to practice and notch up your skills.

The dataset for these exercises is for a library-like website where records of Books, Authors and Publishers are stored. Librarian wants to collect key information about this data, and you will be helping him by writing queries for the same.

For getting started, copy the following files in your main app in your Django project. populate the database with a dump sql file. And GO!

Django ORM — Examples and Practice Problems (1)

from django.db import models

class Author(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
address = models.CharField(max_length=200, null=True)
zipcode = models.IntegerField(null=True)
telephone = models.CharField(max_length=100, null=True)
recommendedby = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='recommended_authors', related_query_name='recommended_authors', null=True)
joindate = models.DateField()
popularity_score = models.IntegerField()
followers = models.ManyToManyField('User', related_name='followed_authors', related_query_name='followed_authors')
def __str__(self):
return self.firstname + ' ' + self.lastname

class Books(models.Model):
title = models.CharField(max_length=100)
genre = models.CharField(max_length=200)
price = models.IntegerField(null=True)
published_date = models.DateField()
author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='books', related_query_name='books')
publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE, related_name='books', related_query_name='books')
def __str__(self):
return self.title

class Publisher(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
recommendedby = models.ForeignKey('Publisher', on_delete=models.CASCADE, null=True)
joindate = models.DateField()
popularity_score = models.IntegerField()
def __str__(self):
return self.firstname + ' ' + self.lastname

class User(models.Model):
username = models.CharField(max_length=100)
email = models.CharField(max_length=100)
def __str__(self):
return self.username

Exercises:

  1. Write a Query using Django ORM to fetch all the books objects from your database.
  2. Write a Query using Django ORM to fetch title and published_date of all books from the database.
  3. Fetch first name and last name of all the new authors ( Authors with popularity_score = 0 are new authors ).
  4. Fetch first name and popularity score of all authors whose first name starts with A and popularity score is greater than or equal to 8.
  5. Fetch first name of all the authors with aa case insensitive in their first name.
  6. Fetch list of all the authors whose ids are in the list = [1, 3, 23, 43, 134, 25].
  7. Fetch list of all the publishers who joined after or in September 2012, output list should only contain first name and join date of publisher. Order by join date.
  8. Fetch ordered list of first 10 last names of Publishers, list must not contain duplicates.
  9. Get the signup date for the last joined Author and Publisher.
  10. Get the first name, last name and join date of the last author who joined.
  11. Fetch list of all authors who joined after or in year 2013
  12. Fetch total price of all the books written by authors with popularity score 7 or higher.
  13. Fetch list of titles of all books written by authors whose first name starts with ‘A’. The result should contain a list of the titles of every book. Not a list of tuples.
  14. Get total price of all the books written by author with pk in list [1, 3, 4]
  15. Produce a list of all the authors along with their recommender.
  16. Produce list of all authors who published their book by publisher pk = 1, output list should be ordered by first name.
  17. Create three new users and add in the followers of the author with pk = 1.
  18. Set the followers list of the author with pk = 2, with only one user.
  19. Add new users in followers of the author with pk = 1.
  20. Remove one user from the followers of the author with pk = 1.
  21. Get first names of all the authors, whose user with pk = 1 is following. ( Without Accessing Author.objects manager )
  22. Fetch list of all authors who wrote a book with “tle” as part of Book Title.
  23. Fetch the list of authors whose names start with ‘A’ case insensitive, and either their popularity score is greater than 5 or they have joined after 2014. with Q objects.
  24. Retrieve a specific object with primary key= 1 from the Author table.
  25. Retrieve the first N=10 records from an Author table.
  26. Retrieve records from a table that match this condition, popularity score = 7. And get the first and last record of that list.
  27. Retrieve all authors who joined after or in the year 2012, popularity score greater than or equal to 4, join date after or with date 12, and first name starts with ‘a’ (case insensitive) without using Q objects.
  28. Retrieve all authors who did not join in 2012.
  29. Retrieve Oldest author, Newest author, Average popularity score of authors, sum of price of all books in database.
  30. Retrieve all authors who have no recommender, recommended by field is null.
  31. Retrieve the books that do not have any authors, where the author is null. Also, retrieve the books whose authors are present, but do not have a recommender, where the author is not null and the author’s recommender is null. (Note that if the condition for the author not being null is not specified and only the condition for the recommender being null is mentioned, all books with both author null and author’s recommender null will be retrieved.)
  32. Total price of books written by author with primary key = 1. ( Aggregation over related model ), oldest book written by author with pk = 1, latest book written by author with pk = 1.
  33. Among the publishers in the Publishers table what is the oldest book any publisher has published.
  34. Average price of all the books in the database.
  35. Maximum popularity score of publisher among all the publishers who published a book for the author with pk = 1. (Reverse Foreign Key hop)
  36. Count the number of authors who have written a book which contains the phrase ‘ab’ case insensitive.
  37. Get all the authors with followers more than 216.
  38. Get average popularity score of all the authors who joined after 20 September 2014.
  39. Generate a list of books whose author has written more than 10 books.
  40. Get the list of books with duplicate titles.

Note: Combining multiple aggregations with annotation will yield the wrong results because joins are used instead of subqueries. For most aggregates there is no way to avoid this problem. Count aggregate has distinct parameter that may help. Consider inspecting the query property of the QuerySet object. ( Taken from docs of django as key information )

Solutions:

from main.models import *
import datetime
from django.db.models import Count, Avg, Sum, Max, Min
from django.db.models import Q, F
ans1 = Books.objects.all()
ans2 = Books.objects.all().values_list('title', 'published_date')
ans3 = Authors.objects.all().filter(popularity_score=0).values_list('firstname', 'lastname')
ans4 = Authors.objects.all().filter(firstname__startswith='a', popularity_score__gte=8).values_list('firstname', 'popularity_score')
ans5 = Authors.objects.all().filter(firstname__icontains='aa').values_list('firstname')
ans6 = Authors.objects.all().filter(pk__in=[1, 3, 23, 43, 134, 25])
ans7 = Authors.objects.all().filter(joindate__gte=datetime.date(year=2012, month=9, day=1)).order_by('joindate').values_list('firstname', 'joindate')
ans8 = Publishers.objects.all().order_by('lastname').values_list('lastname').distinct()[:10]
ans9 = [Authors.objects.all().order_by('joindate').last(),
Publishers.objects.all().order_by('-joindate').first()]
ans10 = Authors.objects.all().order_by('-joindate').values_list('firstname', 'lastname', 'joindate').first()
ans11 = Authors.objects.all().filter(joindate__year__gte=2013)
ans12 = Books.objects.all().filter(author__popularity_score__gte=7).aggregate(total_book_price=Sum('price'))
ans13 = Books.objects.all().filter(author__firstname__contains='a').values_list('title', flat=True)
ans14 = Books.objects.all().filter(author__pk__in=[1, 3, 4]).aggregate('price')
ans15 = Authors.objects.all().values_list('firstname', 'recommendedby__firstname')
ans16 = Authors.objects.all().filter(books__publisher__pk=1)
user1 = Users.objects.create(username='user1', email='user1@test.com')
user2 = Users.objects.create(username='user2', email='user2@test.com')
user3 = Users.objects.create(username='user3', email='user3@test.com')
ans17 = Authors.objects.get(pk=1).followers.add(user1, user2, user3)
ans18 = Authors.objects.get(pk=2).followers.set(user1)
ans19 = Authors.objects.get(pk=1).followers.add(user1)
ans20 = Authors.objects.get(pk=1).followers.remove(user1)
ans21 = Users.objects.get(pk=1).followed_authors.all().values_list('firstname', flat=True)
ans22 = Authors.objects.all().filter(books__title__icontains='tle')
ans23 = Authors.objects.all().filter(Q(firstname__istartswith='a') and ( Q(popularity_score__gt=5) or Q(joindate__year__gt=2014)))
ans24 = Authors.objects.all().get(pk=1)
ans25 = Authors.objects.all()[:10]
qs = Authors.objects.all().filter(popularity_scre=7)
author1 = qs.first()
author2 = qs.last()
ans26 = [author1, author2]
ans27 = Authors.objects.all().filter(joindate__year__gte=2012, popularity_score__gte=4, joindate__day__gte=12, firstame__istartswith='a')
ans28 = Authors.objects.all().exclude(joindate__year=2012)
oldest_author = Authors.objects.all().aggregate(Min('joindate'))
newest_author = Authors.objects.all().aggregate(Max('joindate'))
avg_pop_score = Authors.objects.all().aggregate(Avg('popularity_score'))
sum_price = Books.objects.all().aggregate(Sum('price'))
ans29 = [oldest_author, newest_author, avg_pop_score, sum_price]
ans30 = Authors.objects.all().filter(recommendedby__isnull=True)
one = Books.objects.all().filter(author__isnull=False)
two = Books.objects.all().filter(author__isnull=False, author__recommender__isnull=True)
ans31 = [one, two]
ans32 = Books.objects.all().filter(author__pk=1).aggregate(Sum('price'))
ans33 = Books.objects.all().order_by('published_date').last().title
ans34 = Books.objects.all().aggregate(Avg('price'))
ans35 = Publishers.objects.filter(books__author__pk=1).aggregate(Max('popularity_score'))
ans36 = Authors.objects.filter(books__title__icontains='ab').count()
ans37 = Authors.objects.annotate(f_count=Count('followers')).filter(f_count__gt=216)
ans38 = Authors.objects.filter(joindate__gt=datetime.date(year=2014, month=9, day=20)).aggregate(Avg('popularity_score'))
ans39 = Books.objects.all().annotate(bk_count=Count('author__books')).filter(bk_count__gt=10).distinct()
ans40 = Books.objects.all().annotate(count_title=Count('title')).filter(count_title__gt=1)

And with that we conclude our article. Let me know if you face any problem in setting up an environment or practising problems in the comment section. Suggestions for articles are much appreciated.

Cheers.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Build awareness and adoption for your tech startup with Circuit.

Django ORM — Examples and Practice Problems (2024)

FAQs

What is Django ORM with example? ›

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.

Is Django ORM slow? ›

As you learn more about your problem domain, you need to adapt your code accordingly. All frameworks require upfront knowledge about how the internals work in order to write high performance code. Django is fast, but sometimes it allows you to unwittingly write slow code.

How ORM works in Django? ›

The main goal of ORM is to send data between a database and models in an application. It maps a relation between the database and a model. So, ORM maps object attributes to fields of a table. The main advantage of using ORM is that it makes the entire development process fast and error-free.

What is ORM give an example? ›

ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C#, etc. Sr.No. Let's business code access objects rather than DB tables. Hides details of SQL queries from OO logic.

What is Django ORM interview questions? ›

Basic Django Interview Questions and Answers
  • What is Django? ...
  • Is Django backend or front end? ...
  • What is the latest version of Django? ...
  • What is the difference between Python and Django? ...
  • What architecture does Django use? ...
  • Explain Django Architecture. ...
  • Explain Django's code reusability. ...
  • Is Django easy to learn?

What does {% %} do in Django? ›

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} in Django? ›

The include tag allows you to include a template inside the current template. This is useful when you have a block of content that is the same for many pages.

Is Django ORM faster than SQL? ›

The main benefits of using Django ORM instead of SQL is a huge improvement in development speed, code maintenance, security and ease of development in general.

What are the disadvantages of ORM? ›

Disadvantages of Using ORM Tools
  • Learning how to use ORM tools can be time consuming.
  • They are likely not going to perform better when very complex queries are involved.
  • ORMs are generally slower than using SQL.
Oct 21, 2022

Is SQLAlchemy better than Django ORM? ›

In addition to this, since it interacts directly with the database, you can simply run the queries against the database without actually using the ORM. Plus, SQLAlchemy is much more powerful than Django, albeit with a little higher learning curve.

Why ORM is faster than SQL? ›

Because ORM has a higher level of abstraction and more complexity than SQL, less hands-on management is required; this makes data management more efficient.

Does Django ORM prevent SQL injection? ›

SQL injection protection

Django's querysets are protected from SQL injection since their queries are constructed using query parameterization. A query's SQL code is defined separately from the query's parameters.

What is ORM in REST API? ›

ORM stands for Object-Relational Mapping, it is a technique that allows you to query and manipulate data from a database using objects. You don't have have to write queries anymore, you can use objects to retrieve data.

What is ORM in Python example? ›

An ORM (Object Relational Mapper) is a tool that allows you to interact with your database using the object-oriented paradigm. Therefore, ORMs are generally implemented as libraries in languages that support object-oriented programming.

Why should I use an ORM? ›

ORM is a technique that lets you query and manipulates data from a database using an object-oriented paradigm. It encapsulates the code needed to communicate with the database, so you don't use SQL anymore; you interact directly with an object in the same language you're using.

What is ORM interview questions? ›

Hibernate ORM framework Interview questions
  • What is Hibernate ? ...
  • What are some advantages of Hibernate ? ...
  • What is ORM framework ? ...
  • What is Hibernate configuration file? ...
  • How to print the sql queries in development environment in Hibernate? ...
  • What are the different persistence states of Objects in Hibernate ?
Jun 22, 2018

Is ORM faster than raw SQL queries? ›

There is little research on which technique is faster. Intuitively, Raw SQL should be faster than Eloquent ORM, but exactly how much faster needs to be researched. In particular, when one uses Raw SQL over Eloquent ORM, one makes a trade-off between ease of development, and performance.

Is ORM slower than raw query? ›

Long story short: for anything but the most basic of queries, ORMs require multiple queries to fetch all the data you need. This, more than anything else, is why ORMs are perceptually slower than raw SQL.

Which one is the most popular ORM framework? ›

Hibernate, Sequelize, Entity Framework, SQLAlchemy, and Dapper are the most popular tools in the category "Object Relational Mapper (ORM)". "Easy ORM" is the primary reason developers pick Hibernate over its competitors, while "Good ORM for node.

Why is {% extends %} tag used? ›

The extends tag is used to declare a parent template. It should be the very first tag used in a child template and a child template can only extend up to one parent template. To summarize, parent templates define blocks and child templates will override the contents of those blocks.

Is Django full-stack? ›

Described on Python's official website as “the web framework for perfectionists (with deadlines)”, Django is a full-stack framework for web developers working with Python. Essentially, its aim is to reduce the overall web development process when building web apps.

Is Django frontend or backend? ›

Is Django frontend or backend? Django is an open-source framework for backend web applications based on Python — one of the top web development languages.

What are migrations in Django? ›

Migrations are Django's way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They're designed to be mostly automatic, but you'll need to know when to make migrations, when to run them, and the common problems you might run into.

What is middleware in Django? ›

Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level “plugin” system for globally altering Django's input or output. Each middleware component is responsible for doing some specific function.

What encryption does Django use? ›

By default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST. This should be sufficient for most users: it's quite secure, requiring massive amounts of computing time to break.

Which DB works best with Django? ›

Postgresql is the preferred database for Django applications due to its open-source nature; and it's also ideal for complex queries.

Do professionals use Django? ›

Django is a Python-based web framework giving developers the tools they need for rapid, hassle-free development. You can find that several major companies employ Django for their development projects. Here are 9 global companies using Django: Instagram.

Why use an ORM instead of raw SQL? ›

Developers can use tools called object-relational mappers. They show the data in a structured way that helps users understand the content and layout of a database without using SQL. One of the major benefits is that it saves time compared to entering SQL queries.

Is ORM overkill? ›

Because of the learning curve and the complexity added to the project, ORM might be an overkill for simple projects. Also, if not optimized, it may perform poorly in a project which contains complex queries or requires high efficiency.

Is it OK not to use ORM? ›

If you're not going to use ORM, you should probably define DAOs or persistence and query methods to avoid coupling the model layer with the persistence layer. Otherwise you end up with SQL in your model objects and a forced dependency on your project.

Is Django ORM good? ›

Django's ORM saves developers a lot of time because it allows them to write their data model in a single place, making it easier to update, maintain and reuse code. It also allows for the automatic handling of database schemas. Best of all, your Web Programmers don't have to write SQL.

Is NASA using Django? ›

5. NASA. The website of the United States National Aeronautics and Space Administration (NASA) is built using Django.

What famous websites use Django? ›

The web framework of Python — Django is an excellent solution for building scalable web applications. Such companies as Instagram, Pinterest, Mozilla, Spotify, Eventbrite, and National Geographic use Django apps.

Can FastAPI replace Django? ›

In conclusion, Django is perfect if you want to build robust full-stack web applications because it has several functionalities and works very well in production. On the other hand FastAPI is perfect if you're looking for high performance or scalable applications.

Is Django more powerful than Flask? ›

Due to fewer abstraction layers, Flask is faster than Django. It is a full-stack framework with almost everything built-in — a batteries-included approach. It is a microframework with minimalistic features that let developers integrate any plugins and libraries.

Why Flask is preferred over Django? ›

Flask will make your life easier than Django if you're looking to create a simple web app with a few static pages. Many programmers find Flask to be easily scalable for smaller web applications. It comes with a built-in development server and fast debugger.

What is the best ORM tool? ›

8 Effective Online Reputation Management (ORM) Tools
  • Radian6. Radian6 - an online reputation management tool - helps to manage and monitor brand reputation across different online platforms. ...
  • Sentiment Metrics. ...
  • UberVU. ...
  • ReviewTrackers. ...
  • Talkwalker. ...
  • Go Fish Digital Complaint Search. ...
  • Image Raider. ...
  • Yotpo.
Mar 28, 2022

Which is better ORM or raw query? ›

ORMs provide a code-first API to express queries, whereas raw SQL queries are often expressed as plain strings. These query strings are often more concise than the equivalent ORM operation and allow queries to be represented in a language-agnostic way.

Which is the best ORM for Python? ›

7 Best Free and Open Source Python Object-Relational Mapping Software
Python Object-Relational Mapping Software
PonyBilled as the smartest Python ORM
Tortoise ORMEasy-to-use asyncio ORM inspired by Django
StormDesigned to work with thin relational databases and big systems
4 more rows
May 7, 2022

Should you use raw SQL in Django? ›

Django uses the primary key to identify model instances, so it must always be included in a raw query.

Is Django ORM Secure? ›

Django's ORM uses parameterized statements everywhere, so it is highly resistant to SQLi. Thus, if you're using the ORM to make database queries you can be fairly confident that your app is safe.

Is JSON an ORM? ›

Yes there is JSON ODM. Exactly what you are looking for.

How many types of ORM are there? ›

There are many types of ORM languages like Django ORM, Dapper ORM, JOOQ ORM, SQL Alchemy, etc.

How does Python ORM work? ›

ORMs provide a high-level abstraction upon a relational database that allows a developer to write Python code instead of SQL to create, read, update and delete data and schemas in their database.

What is Django ORM called? ›

Django ORM provides an elegant and powerful way to interact with the database. ORM stands for Object Relational Mapper. It is just a fancy word describing how to access the data stored in the database in Object Oriented fashion. Start Django shell using the shell command.

Is ORM better than SQL? ›

Developers can use tools called object-relational mappers. They show the data in a structured way that helps users understand the content and layout of a database without using SQL. One of the major benefits is that it saves time compared to entering SQL queries.

Why we use ORM instead of SQL? ›

Because ORM has a higher level of abstraction and more complexity than SQL, less hands-on management is required; this makes data management more efficient.

Is Django ORM a framework? ›

The Django web framework includes a default object-relational mapping layer (ORM) that can be used to interact with data from various relational databases such as SQLite, PostgreSQL, and MySQL. Django allows us to add, delete, modify and query objects, using an API called ORM. ORM stands for Object Relational Mapping.

Top Articles
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 5938

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.