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`` objects, and
8 each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position``
9 field, which specifies the ``Reporter``'s position for the given article
10 (e.g. "Staff writer").
13 from django
.db
import models
15 class Reporter(models
.Model
):
16 first_name
= models
.CharField(max_length
=30)
17 last_name
= models
.CharField(max_length
=30)
19 def __unicode__(self
):
20 return u
"%s %s" % (self
.first_name
, self
.last_name
)
22 class Article(models
.Model
):
23 headline
= models
.CharField(max_length
=100)
24 pub_date
= models
.DateField()
26 def __unicode__(self
):
29 class Writer(models
.Model
):
30 reporter
= models
.ForeignKey(Reporter
)
31 article
= models
.ForeignKey(Article
)
32 position
= models
.CharField(max_length
=100)
34 def __unicode__(self
):
35 return u
'%s (%s)' % (self
.reporter
, self
.position
)
37 __test__
= {'API_TESTS':"""
38 # Create a few Reporters.
39 >>> r1 = Reporter(first_name='John', last_name='Smith')
41 >>> r2 = Reporter(first_name='Jane', last_name='Doe')
45 >>> from datetime import datetime
46 >>> a = Article(headline='This is a test', pub_date=datetime(2005, 7, 27))
49 # Create a few Writers.
50 >>> w1 = Writer(reporter=r1, article=a, position='Main writer')
52 >>> w2 = Writer(reporter=r2, article=a, position='Contributor')
55 # Play around with the API.
56 >>> a.writer_set.select_related().order_by('-position')
57 [<Writer: John Smith (Main writer)>, <Writer: Jane Doe (Contributor)>]
59 <Reporter: John Smith>
63 <Article: This is a test>
65 <Article: This is a test>
66 >>> r1.writer_set.all()
67 [<Writer: John Smith (Main writer)>]