models.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """
  2. Many-to-many relationships via an intermediary table
  3. For many-to-many relationships that need extra fields on the intermediary
  4. table, use an intermediary model.
  5. In this example, an ``Article`` can have multiple ``Reporter`` objects, and
  6. each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position``
  7. field, which specifies the ``Reporter``'s position for the given article
  8. (e.g. "Staff writer").
  9. """
  10. from __future__ import unicode_literals
  11. from django.db import models
  12. from django.utils.encoding import python_2_unicode_compatible
  13. @python_2_unicode_compatible
  14. class Reporter(models.Model):
  15. first_name = models.CharField(max_length=30)
  16. last_name = models.CharField(max_length=30)
  17. def __str__(self):
  18. return "%s %s" % (self.first_name, self.last_name)
  19. @python_2_unicode_compatible
  20. class Article(models.Model):
  21. headline = models.CharField(max_length=100)
  22. pub_date = models.DateField()
  23. def __str__(self):
  24. return self.headline
  25. @python_2_unicode_compatible
  26. class Writer(models.Model):
  27. reporter = models.ForeignKey(Reporter, models.CASCADE)
  28. article = models.ForeignKey(Article, models.CASCADE)
  29. position = models.CharField(max_length=100)
  30. def __str__(self):
  31. return '%s (%s)' % (self.reporter, self.position)