如何在一个模型中指定父子关系? [英] How to specify Parent-Child relationship within one Model?
本文介绍了如何在一个模型中指定父子关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有以下代码:
class FamilyMember(models.Model):
user = models.OneToOneField(User)
我有以下情况:
a1 = FamilyMember.objects.get(id=1)
a1.first_name = 'John'
a1.last_name = 'Smith'
(a1 is a parent of a2)
a2 = FamilyMember.objects.get(id=2)
a2.first_name = 'Mark'
a2.last_name = 'Smith'
(a2 is a child of a1 and parent of a3 in the same time)
a3 = FamilyMember.objects.get(id=3)
a3.first_name = 'Jason'
a3.last_name = 'Smith'
(a3 is a child of a2)
我如何在一个模型中完成这种关系?
How can i accomplish that kind of relationships within one model ?
推荐答案
您可以使用简单的ForeignKey来实现表示父级的self:
You can do this with a simple ForeignKey to self to indicate the parent:
parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
现在您可以执行 a2.parent = a1
,并会自动访问 a1.children.all ()
。
Now you can do a2.parent = a1
, and will automatically get access to a1.children.all()
.
这篇关于如何在一个模型中指定父子关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文