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:

Copied!
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.

Copied!
python manage.py 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 models.py).

Copied!
from .models import Book, Author

Run your first select query:

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

Lets create an author and book object:

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

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

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

Now lets run the query

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

Let’s add a where clause to our select query

Copied!
>>> 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

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

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

Copied!
>>> 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.

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

Leave a Reply

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