2006-05-02 01:31:56 +00: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):
|
2007-08-05 05:14:46 +00:00
|
|
|
name = CharField(max_length=100, core=True)
|
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)
|
2006-05-02 01:31:56 +00:00
|
|
|
parent = ForeignKey(Parent)
|
|
|
|
|
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
|
|
|
"""}
|