How to query django database

Basic Django Database Queries

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 manage.py shellCode language: CSS (css)

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 models.py).

from .models import Book, AuthorCode language: JavaScript (javascript)

Run your first select query:

>>> Author.objects.all() 
[]
>>> Book.objects.all()
[]Code language: CSS (css)

Lets create an author and book object:

>>> hawking = Author(name="Stephen hawking")
>>> hawking.save()
>>> history_of_time = Book(name="history of time", author=hawking)
>>> history_of_time.save()Code language: JavaScript (javascript)

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")Code language: JavaScript (javascript)

Now lets run the query

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

Let’s add a where clause to our select query

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

To get the details about the author of a given book

>>> book = Book.objects.first() #getting the first book object
>>> book.author.name # lookup on related model
u'Stephen hawking'Code language: PHP (php)

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

>>> hawking.book_set.all()
[<Book: Book object>]Code language: CSS (css)

_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.

Conclusion

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 🙂

Comments

Leave a Reply