How to specify Parent-Child relationship within one Model?

后端 未结 2 1427
北荒
北荒 2020-12-17 06:39

For example I have following code:

class FamilyMember(models.Model):
    user = models.OneToOneField(User)

And I have following situations:

2条回答
  •  一整个雨季
    2020-12-17 07:04

    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')
    

    Now you can do a2.parent = a1, and will automatically get access to a1.children.all().

提交回复
热议问题