parts/django/tests/modeltests/m2m_intermediary/models.py
changeset 69 c6bca38c1cbf
equal deleted inserted replaced
68:5ff1fc726848 69:c6bca38c1cbf
       
     1 """
       
     2 9. Many-to-many relationships via an intermediary table
       
     3 
       
     4 For many-to-many relationships that need extra fields on the intermediary
       
     5 table, use an intermediary model.
       
     6 
       
     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").
       
    11 """
       
    12 
       
    13 from django.db import models
       
    14 
       
    15 class Reporter(models.Model):
       
    16     first_name = models.CharField(max_length=30)
       
    17     last_name = models.CharField(max_length=30)
       
    18 
       
    19     def __unicode__(self):
       
    20         return u"%s %s" % (self.first_name, self.last_name)
       
    21 
       
    22 class Article(models.Model):
       
    23     headline = models.CharField(max_length=100)
       
    24     pub_date = models.DateField()
       
    25 
       
    26     def __unicode__(self):
       
    27         return self.headline
       
    28 
       
    29 class Writer(models.Model):
       
    30     reporter = models.ForeignKey(Reporter)
       
    31     article = models.ForeignKey(Article)
       
    32     position = models.CharField(max_length=100)
       
    33 
       
    34     def __unicode__(self):
       
    35         return u'%s (%s)' % (self.reporter, self.position)
       
    36