2005-12-17 06:15:07 +08:00
|
|
|
"""
|
|
|
|
24. Mutually referential many-to-one relationships
|
|
|
|
|
|
|
|
To define a many-to-one relationship, use ``ForeignKey()`` .
|
|
|
|
"""
|
|
|
|
|
|
|
|
from django.db.models import *
|
|
|
|
|
|
|
|
class Parent(Model):
|
|
|
|
name = CharField(maxlength=100)
|
2006-01-29 01:06:05 +08:00
|
|
|
bestchild = ForeignKey("Child", null=True, related_name="favoured_by")
|
2006-01-30 08:38:23 +08:00
|
|
|
|
2005-12-17 06:15:07 +08:00
|
|
|
class Child(Model):
|
|
|
|
name = CharField(maxlength=100)
|
|
|
|
parent = ForeignKey(Parent)
|
2006-01-30 08:38:23 +08:00
|
|
|
|
2005-12-17 06:15:07 +08:00
|
|
|
API_TESTS = """
|
|
|
|
# Create a Parent
|
|
|
|
>>> q = Parent(name='Elizabeth')
|
|
|
|
>>> q.save()
|
|
|
|
|
|
|
|
# Create some children
|
2006-02-27 22:23:52 +08:00
|
|
|
>>> c = q.child_set.create(name='Charles')
|
|
|
|
>>> e = q.child_set.create(name='Edward')
|
2005-12-17 06:15:07 +08:00
|
|
|
|
|
|
|
# Set the best child
|
2006-01-30 08:38:23 +08:00
|
|
|
>>> q.bestchild = c
|
2005-12-17 06:15:07 +08:00
|
|
|
>>> q.save()
|
|
|
|
|
|
|
|
>>> q.delete()
|
|
|
|
|
|
|
|
"""
|