SoFunction
Updated on 2024-11-17

Example of how to access foreign key values for data models in Django

First set up a data model about books (book):

from  import models

class Publisher():
  name = (max_length=30)
  address = (max_length=50)
  city = (max_length=60)
  state_province = (max_length=30)
  country = (max_length=50)
  website = ()

  def __unicode__(self):
    return 

class Author():
  first_name = (max_length=30)
  last_name = (max_length=40)
  email = ()

  def __unicode__(self):
    return u'%s %s' % (self.first_name, self.last_name)

class Book():
  title = (max_length=100)
  authors = (Author)
  publisher = (Publisher)
  publication_date = ()

  def __unicode__(self):
    return 

Accessing Foreign Key Values

When you get a ForeignKey field, you get the associated data model object. For example.

>>> b = (id=50)
>>> 
<Publisher: Apress Publishing>
>>> 
u'/'

For relationships defined with ``ForeignKey``, it is possible to trace back in reverse on the other side of the relationship, but the relationship is slightly different due to asymmetry. Getting books directly from a ``publisher`` object, using publisher.book_set.all(), is as follows:

>>> p = (name='Apress Publishing')
>>> p.book_set.all()
[<Book: The Django Book>, <Book: Dive Into Python>, ...]

In fact, book_set is just a QuerySet, so it can be used like a QuerySet to filter and slice data, for example:

>>> p = (name='Apress Publishing')
>>> p.book_set.filter(name__icontains='django')
[<Book: The Django Book>, <Book: Pro Django>]

The attribute name book_set is composed of the lowercase of the model name (e.g., book) plus _set.