Skip to content

Musings of an Anonymous Geek

Made with only the finest 1's and 0's

Menu
  • About
  • Search Results
Menu

Representing Relationships in Django Templates Without Writing Extra Code (RelatedManager and ManyRelatedManager)

Posted on August 31, 2009August 31, 2009 by bkjones

I’m writing an application that deals with some slightly complex relationships. There are several offices, and each office has several workers. Workers can have multiple projects, and each project can have multiple workers. In addition, each project can serve multiple clients.

Here’s what that’d look like in a Django models.py file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Office(models.Model):
   office_code = models.CharField(max_length=24, blank=True)
   street_num = models.CharField(max_length=24)
   street_name = models.CharField(max_length=64)
   bldg_no = models.CharField(max_length=12, blank=True)
   suite = models.CharField(max_length=12, blank=True)
   city = models.CharField(max_length=100)
   state = USStateField() # grandiose assumption
   zipcode = models.CharField(max_length=10)
   main_phone = PhoneNumberField()
   site_mgr = models.ForeignKey(User, unique=True)
 
class Worker(models.Model):
   user = models.ForeignKey(User, unique=True)
   extension = models.CharField(max_length=8)
   office = models.ForeignKey(Office)
 
class Client(models.Model):
   fname = models.CharField(max_length=64)
   lname = models.CharField(max_length=64)
   street_num = models.CharField(max_length=24, blank=True)
   street_name = models.CharField(max_length=128, blank=True)
   apt_no = models.CharField(max_length=24, blank=True)
   city = models.CharField(max_length=128, blank=True)
   state = USStateField(blank=True)
   zipcode = models.CharField(max_length=10, blank=True)
 
class Project(models.Model):
   date_started = models.DateTimeField()
   worker = models.ManyToManyField(Worker)
   office = models.ForeignKey(Office)
   client = models.ManyToManyField(Client)

While writing the template for my worker detail page, I decided that I didn’t want to just list the projects for that worker, but I also wanted to list the clients for each project. I ran into a bit of an issue at first in doing this. I tried something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
{% block content %}
   <h2>Projects for {{object.user.first_name}} {{object.user.last_name}}</h2>
   <ul>
   {% for project in object.projects %}
      <li><a href="{{project.get_absolute_url}}">{{project.id}} (Opened: {{project.date_started.date}})</a>
      <ul>
         {% for obj in project.get_clients %}
            <li>{{obj.lname}}, {{obj.fname}}</li>
         {% endfor %}
      </ul>
   <h2>Clients for project {{project.id}}</h2>
{% endfor %}</ul>
{% endblock %}

Looking back at the models, you’ll note that there’s no “projects” attribute of the Worker class. There’s also no “get_clients” method for the Project class. After reading some forum and blog posts, I got the idea to add these to my models manually. It seems a lot of people solve similar issues this way, and I don’t believe it’s necessary, which is why I’m posting this. What I added to my models looked something like this:

1
2
3
4
5
6
7
8
9
10
11
###
### in Worker model
###
def projects(self):
   return self.project_set.filter(worker = self.pk)
 
###
### in Project model
###
def get_clients(self):
   return self.client_set.all()

Adding these to the models actually does solve the problem, but it’s reinventing the wheel. Perhaps at some point in history Django’s ORM didn’t have the functionality it does now, but these days Django takes care of accessing the objects of related entities for you through the use of the RelatedManager (for one-to-one, foreign key relationships) and the ManyRelatedManager (for many-to-many relationships).

When you create a ForeignKey field or ManyToMany field in a Django model, Django’s ORM becomes aware of the relationship, and implements lots of shortcuts to help you in managing/exploiting it.

After reading some online documentation (see the “Related Objects” area, for one), I was able to get all of the data I wanted into my template without adding a single character of code to my models, which is what I had hoped for. Here’s the right way to do this, unless I’m mistaken (please let me know the best way if I am):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{% block content %}
<h2>Projects for {{object.user.first_name}} {{object.user.last_name}}</h2>
<ul>
   {% for project in object.project_set.all %}
      <li><a href="{{project.get_absolute_url}}">{{project.id}} (Opened: {{project.date_started.date}})</a>
      <ul>
         <h2>Clients for project {{project.id}}</h2>
         {% for obj in project.client.all %}
            <li>{{obj.lname}}, {{obj.fname}}</li>
         {% endfor %}
      </ul>
   {% endfor %}
</ul>
{% endblock %}

I’ve replaced “object.projects” with “object.project_set.all”. Note that, in a Django template, unless you specify otherwise, the name of a single object passed to a template is “object”, so in this case, “object” is a “Worker” object. The Worker model makes no mention at all of projects, and yet I’m able to easily grab data about project objects. This is because Django’s ORM actually gives you access to related object data from either side of a relationship. Since the Project model has a ManyToMany field referencing Worker, you can access project data from the worker object by using “object._set.all”, where is replaced with the lower-cased name of the model that points to “object”. Hence, “object.project_set.all”.

Now, in the second case, I’ve replaced “project.get_clients” with “project.client.all”. The Project model directly contains a field named “client” that is a ForeignKey to the Client model. When this condition exists, Django will happily traverse the relationship for you by just referencing the model’s field directly! The “all” method is a standard method of any Manager object I’m aware of, and it’s inherited by the RelatedManager and ManyRelatedManager objects.

One interesting thing I found, too, was that there’s no mention of “RelatedManager” or “ManyRelatedManager” in the online Django documentation. This is highly unusual. In my experience, Django’s documentation blows away the docs for just about any project in existence. Did I miss something?

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to share on Tumblr (Opens in new window) Tumblr
  • Click to share on Facebook (Opens in new window) Facebook

Recent Posts

  • Auditing Your Data Migration To ClickHouse Using ClickHouse Local
  • ClickHouse Cheat Sheet 2024
  • User Activation With Django and Djoser
  • Python Selenium Webdriver Notes
  • On Keeping A Journal and Journaling
  • What Geeks Could Learn From Working In Restaurants
  • What I’ve Been Up To
  • PyCon Talk Proposals: All You Need to Know And More
  • Sending Alerts With Graphite Graphs From Nagios
  • The Python User Group in Princeton (PUG-IP): 6 months in

Categories

  • Apple
  • Big Ideas
  • Books
  • CodeKata
  • Database
  • Django
  • Freelancing
  • Hacks
  • journaling
  • Leadership
  • Linux
  • LinuxLaboratory
  • Loghetti
  • Me stuff
  • Other Cool Blogs
  • PHP
  • Productivity
  • Python
  • PyTPMOTW
  • Ruby
  • Scripting
  • Sysadmin
  • Technology
  • Testing
  • Uncategorized
  • Web Services
  • Woodworking

Archives

  • January 2024
  • May 2021
  • December 2020
  • January 2014
  • September 2012
  • August 2012
  • February 2012
  • November 2011
  • October 2011
  • June 2011
  • April 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • September 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
  • May 2008
  • April 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007
  • February 2007
  • January 2007
  • December 2006
  • November 2006
  • September 2006
  • August 2006
  • July 2006
  • June 2006
  • April 2006
  • March 2006
  • February 2006
  • January 2006
  • December 2005
  • November 2005
  • October 2005
  • September 2005
  • August 2005
  • July 2005
  • June 2005
  • May 2005
  • April 2005
  • March 2005
  • February 2005
  • January 2005
  • December 2004
  • November 2004
  • October 2004
  • September 2004
  • August 2004
© 2025 Musings of an Anonymous Geek | Powered by Minimalist Blog WordPress Theme
Menu
  • About
  • Search Results