Just starting to learn Django and thought of keeping some useful notes for myself. Django API’s could get a little confusing in the beginning, but it’s pretty wonderful once you get a hang of it. I’ve started to enjoy them as long as it doesn’t get too tricky :). Here’s an example of using the Author and Book model to get list of books for an author AND to get the data about an author from a book.
class Author(models.Model): name = models.CharField(max_length=100, verbose_name='Name') email = models.CharField(max_length=100, verbose_name='Email') ... ... class Book(models.Model): author = models.ForeignKey(Author, related_name='books') name = models.CharField(max_length=100, verbose_name='Name') ... ...
1. Get all books belonging to some author
author = Author.objects.get(id=1234)
books = author.books.all()
You can use any query expression with get(), just like with filter(). Note that there is a difference between using get(), and using filter() with a slice of . If there are no results that match the query, get() will raise a DoesNotExist exception. This exception is an attribute of the model class that the query is being performed on – so in the code above, if there is no Author object with a id of 1234, Django will raise Author.DoesNotExist exception.
2. Get author’s name and email for the book ‘Mahabharatha’
book = Book.objects.filter(name=’Mahabharatha’)
author = book.author
author_name = author.name
author_email = author.email
print ‘%s, %s’ % (author_name, author_email)