models.py 810 B

123456789101112131415161718192021222324252627282930313233343536
  1. """
  2. 24. Mutually referential many-to-one relationships
  3. Strings can be used instead of model literals to set up "lazy" relations.
  4. """
  5. from django.db.models import *
  6. class Parent(Model):
  7. name = CharField(max_length=100)
  8. # Use a simple string for forward declarations.
  9. bestchild = ForeignKey("Child", null=True, related_name="favoured_by")
  10. class Child(Model):
  11. name = CharField(max_length=100)
  12. # You can also explicitally specify the related app.
  13. parent = ForeignKey("mutually_referential.Parent")
  14. __test__ = {'API_TESTS':"""
  15. # Create a Parent
  16. >>> q = Parent(name='Elizabeth')
  17. >>> q.save()
  18. # Create some children
  19. >>> c = q.child_set.create(name='Charles')
  20. >>> e = q.child_set.create(name='Edward')
  21. # Set the best child
  22. >>> q.bestchild = c
  23. >>> q.save()
  24. >>> q.delete()
  25. """}