2
9. Many-to-many relationships via an intermediary table
4
For many-to-many relationships that need extra fields on the intermediary
5
table, use an intermediary model.
7
In this example, an ``Article`` can have multiple ``Reporter``s, and each
8
``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field,
9
which specifies the ``Reporter``'s position for the given article (e.g. "Staff
13
from django.core import meta
15
class Reporter(meta.Model):
16
first_name = meta.CharField(maxlength=30)
17
last_name = meta.CharField(maxlength=30)
20
return "%s %s" % (self.first_name, self.last_name)
22
class Article(meta.Model):
23
headline = meta.CharField(maxlength=100)
24
pub_date = meta.DateField()
29
class Writer(meta.Model):
30
reporter = meta.ForeignKey(Reporter)
31
article = meta.ForeignKey(Article)
32
position = meta.CharField(maxlength=100)
35
return '%r (%s)' % (self.get_reporter(), self.position)
38
# Create a few Reporters.
39
>>> r1 = reporters.Reporter(first_name='John', last_name='Smith')
41
>>> r2 = reporters.Reporter(first_name='Jane', last_name='Doe')
45
>>> from datetime import datetime
46
>>> a = articles.Article(headline='This is a test', pub_date=datetime(2005, 7, 27))
49
# Create a few Writers.
50
>>> w1 = writers.Writer(reporter=r1, article=a, position='Main writer')
52
>>> w2 = writers.Writer(reporter=r2, article=a, position='Contributor')
55
# Play around with the API.
56
>>> a.get_writer_list(order_by=['-position'], select_related=True)
57
[John Smith (Main writer), Jane Doe (Contributor)]
66
>>> r1.get_writer_list()
67
[John Smith (Main writer)]