Basic Django Database Queries

Haris Bin Nasir Avatar



In this article, we will take a look at basic Django database queries, throughout the tutorial I’ll provide you with helpful code examples that will aid your learning about basic Django database queries.

Django ORM is a strong abstraction that allows you to store and retrieve data from a database without having to write your own SQL queries.

Introduction: Basic Django Database Queries

Let’s assume the following models:

class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author)

Assume you’ve added the above code to a Django app and performed the migrate command (so that your database is created). Start the Django shell by typing django in the command prompt.

python shell

This launches a typical Python shell with relevant Django modules loaded, allowing you to focus on the crucial sections right away.

To begin, import the models we just defined (I assume this is done in a file called

from .models import Book, Author

Run your first select query:

>>> Author.objects.all() [] >>> Book.objects.all() []

Lets create an author and book object:

>>> hawking = Author(name="Stephen hawking") >>> >>> history_of_time = Book(name="history of time", author=hawking) >>>

or create model objects with the create function and save them in a single line of code.

>>> wings_of_fire = Book.objects.create(name="Wings of Fire", author="APJ Abdul Kalam")

Now lets run the query

>>> Book.objects.all() [<Book: Book object>] >>> book = Book.objects.first() #getting the first book object >>> u'history of time'

Let’s add a where clause to our select query

>>> Book.objects.filter(name='nothing') [] >>> Author.objects.filter(name__startswith='Ste') [<Author: Author object>]

To get the details about the author of a given book

>>> book = Book.objects.first() #getting the first book object >>> # lookup on related model u'Stephen hawking'

To get all the books published by Stephen Hawking (Lookup book by its author)

>>> hawking.book_set.all() [<Book: Book object>]

_set is the notation used for “Reverse lookups” i.e. while the lookup field is on the Book model, we can use book_set on an author object to get all his/her books.


I hope you found this tutorial on how to perform queries on the data in your database for a Django project useful. As always, If you have found this tutorial useful do not forget to share it and leave a comment if you have any questions. Happy Coding

Leave a Reply

Your email address will not be published. Required fields are marked *