models.py 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. """
  2. Relating an object to itself, many-to-one
  3. To define a many-to-one relationship between a model and itself, use
  4. ``ForeignKey('self', ...)``.
  5. In this example, a ``Category`` is related to itself. That is, each
  6. ``Category`` has a parent ``Category``.
  7. Set ``related_name`` to designate what the reverse relationship is called.
  8. """
  9. from django.db import models
  10. from django.utils.encoding import python_2_unicode_compatible
  11. @python_2_unicode_compatible
  12. class Category(models.Model):
  13. name = models.CharField(max_length=20)
  14. parent = models.ForeignKey('self', models.SET_NULL, blank=True, null=True, related_name='child_set')
  15. def __str__(self):
  16. return self.name
  17. @python_2_unicode_compatible
  18. class Person(models.Model):
  19. full_name = models.CharField(max_length=20)
  20. mother = models.ForeignKey('self', models.SET_NULL, null=True, related_name='mothers_child_set')
  21. father = models.ForeignKey('self', models.SET_NULL, null=True, related_name='fathers_child_set')
  22. def __str__(self):
  23. return self.full_name