We're trying once again to build a web-based tool to help us manage Software Carpentry workshops. We're using Django, which despite its age is still the most widely used (and best documented) web programming framework for Python. It's been a few years since I built anything in it, though, and I'm stumbling over a few things.
For example, my data model looks like this (with lots of irrelevant stuff stripped out):
class Person(models.Model):
'''Someone we know.'''
email = models.CharField(max_length=STR_LONG, unique=True, null=True)
class Event(models.Model):
'''A workshop or other event.'''
slug = models.CharField(max_length=STR_LONG, unique=True)
class Role(models.Model):
'''The kinds of things people can do at workshops.'''
name = models.CharField(max_length=STR_MED)
class Task(models.Model):
'''Someone did something at some workshop.'''
event = models.ForeignKey(Event)
person = models.ForeignKey(Person)
role = models.ForeignKey(Role)
One of the pages in the application displays information about a particular event. I want to add the names of all the people who were instructors at that event to the page. If I was using SQL directly, I'd write something like:
select Event.slug, group_contact(Person.email, ', ')
from Person join Event join Role join Task
on Person.id=Task.person and Event.id=Task.event and Role.id=Task.role
where Role.name='instructor'
group by Event.id;
How can I do this with Django's ORM? According to this Stack Overflow question, I can use the 'regroup' tag in the view or build a custom aggregator. The former is complicated by the multi-step nature of the join, and the latter feels... complicated. My instinct is that I ought to be able to attach all the Person
objects corresponding to instructors at a particular Event
to that event, then loop over them in my view. If you know how to do this, I'd be grateful for a pointer.