Model field reference

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()
print books

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 [0]. 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 =
author_name =
author_email =
print ‘%s, %s’ % (author_name, author_email)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s