models.py 880 B

123456789101112131415161718192021222324252627282930313233
  1. """
  2. Multiple many-to-many relationships between the same two tables
  3. In this example, an ``Article`` can have many "primary" ``Category`` objects
  4. and many "secondary" ``Category`` objects.
  5. Set ``related_name`` to designate what the reverse relationship is called.
  6. """
  7. from django.db import models
  8. class Category(models.Model):
  9. name = models.CharField(max_length=20)
  10. class Meta:
  11. ordering = ('name',)
  12. def __str__(self):
  13. return self.name
  14. class Article(models.Model):
  15. headline = models.CharField(max_length=50)
  16. pub_date = models.DateTimeField()
  17. primary_categories = models.ManyToManyField(Category, related_name='primary_article_set')
  18. secondary_categories = models.ManyToManyField(Category, related_name='secondary_article_set')
  19. class Meta:
  20. ordering = ('pub_date',)
  21. def __str__(self):
  22. return self.headline