2006-05-02 01:31:56 +00:00
|
|
|
"""
|
|
|
|
20. Multiple many-to-many relationships between the same two tables
|
|
|
|
|
2008-08-12 14:15:38 +00:00
|
|
|
In this example, an ``Article`` can have many "primary" ``Category`` objects
|
|
|
|
and many "secondary" ``Category`` objects.
|
2006-05-02 01:31:56 +00:00
|
|
|
|
|
|
|
Set ``related_name`` to designate what the reverse relationship is called.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from django.db import models
|
2012-08-12 10:32:08 +00:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2011-10-13 18:04:12 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 01:31:56 +00:00
|
|
|
class Category(models.Model):
|
2007-08-05 05:14:46 +00:00
|
|
|
name = models.CharField(max_length=20)
|
2013-09-03 18:22:21 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
class Meta:
|
2013-09-03 18:22:21 +00:00
|
|
|
ordering = ('name',)
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
def __str__(self):
|
2006-05-02 01:31:56 +00:00
|
|
|
return self.name
|
|
|
|
|
2013-09-03 18:22:21 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 01:31:56 +00:00
|
|
|
class Article(models.Model):
|
2007-08-05 05:14:46 +00:00
|
|
|
headline = models.CharField(max_length=50)
|
2006-05-02 01:31:56 +00:00
|
|
|
pub_date = models.DateTimeField()
|
|
|
|
primary_categories = models.ManyToManyField(Category, related_name='primary_article_set')
|
|
|
|
secondary_categories = models.ManyToManyField(Category, related_name='secondary_article_set')
|
2013-09-03 18:22:21 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
class Meta:
|
2013-09-03 18:22:21 +00:00
|
|
|
ordering = ('pub_date',)
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
def __str__(self):
|
2006-05-02 01:31:56 +00:00
|
|
|
return self.headline
|