2006-05-02 01:31:56 +00:00
|
|
|
"""
|
|
|
|
24. Mutually referential many-to-one relationships
|
|
|
|
|
2008-02-26 21:13:16 +00:00
|
|
|
Strings can be used instead of model literals to set up "lazy" relations.
|
2006-05-02 01:31:56 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
from django.db.models import *
|
|
|
|
|
|
|
|
class Parent(Model):
|
2007-08-05 05:14:46 +00:00
|
|
|
name = CharField(max_length=100, core=True)
|
2008-02-26 21:13:16 +00:00
|
|
|
|
|
|
|
# Use a simple string for forward declarations.
|
2006-05-02 01:31:56 +00:00
|
|
|
bestchild = ForeignKey("Child", null=True, related_name="favoured_by")
|
|
|
|
|
|
|
|
class Child(Model):
|
2007-08-05 05:14:46 +00:00
|
|
|
name = CharField(max_length=100)
|
2008-02-26 21:13:16 +00:00
|
|
|
|
|
|
|
# You can also explicitally specify the related app.
|
|
|
|
parent = ForeignKey("mutually_referential.Parent")
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2006-08-27 13:59:47 +00:00
|
|
|
__test__ = {'API_TESTS':"""
|
2006-05-02 01:31:56 +00:00
|
|
|
# Create a Parent
|
|
|
|
>>> q = Parent(name='Elizabeth')
|
|
|
|
>>> q.save()
|
|
|
|
|
|
|
|
# Create some children
|
|
|
|
>>> c = q.child_set.create(name='Charles')
|
|
|
|
>>> e = q.child_set.create(name='Edward')
|
|
|
|
|
|
|
|
# Set the best child
|
|
|
|
>>> q.bestchild = c
|
|
|
|
>>> q.save()
|
|
|
|
|
|
|
|
>>> q.delete()
|
|
|
|
|
2006-08-27 13:59:47 +00:00
|
|
|
"""}
|