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