models.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """
  2. Many-to-many relationships
  3. To define a many-to-many relationship, use ``ManyToManyField()``.
  4. In this example, an ``Article`` can be published in multiple ``Publication``
  5. objects, and a ``Publication`` has multiple ``Article`` objects.
  6. """
  7. from django.db import models
  8. class Publication(models.Model):
  9. title = models.CharField(max_length=30)
  10. def __str__(self):
  11. return self.title
  12. class Meta:
  13. ordering = ('title',)
  14. class Tag(models.Model):
  15. id = models.BigAutoField(primary_key=True)
  16. name = models.CharField(max_length=50)
  17. def __str__(self):
  18. return self.name
  19. class Article(models.Model):
  20. headline = models.CharField(max_length=100)
  21. # Assign a string as name to make sure the intermediary model is
  22. # correctly created. Refs #20207
  23. publications = models.ManyToManyField(Publication, name='publications')
  24. tags = models.ManyToManyField(Tag, related_name='tags')
  25. def __str__(self):
  26. return self.headline
  27. class Meta:
  28. ordering = ('headline',)
  29. # Models to test correct related_name inheritance
  30. class AbstractArticle(models.Model):
  31. class Meta:
  32. abstract = True
  33. publications = models.ManyToManyField(Publication, name='publications', related_name='+')
  34. class InheritedArticleA(AbstractArticle):
  35. pass
  36. class InheritedArticleB(AbstractArticle):
  37. pass