Looking for django Answers? Try Ask4KnowledgeBase
Looking for django Keywords? Try Ask4Keywords

Django Basic Django DB queries


Django ORM is a powerful abstraction that lets you store and retrieve data from the database without writing sql queries yourself.

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)

Assuming you've added the above code to a django application and run the migrate command (so that your database is created). Start the Django shell by

python manage.py shell

This starts the standard python shell but with relevant Django libraries imported, so that you can directly focus on the important parts.

Start by importing the models we just defined (I am assuming this is done in a file models.py)

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")
>>> hawking.save()
>>> history_of_time = Book(name="history of time", author=hawking)
>>> history_of_time.save()

or use create function to create model objects and save in one line 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
>>> book.name
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
>>> book.author.name # 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.