How to specify Parent-Child relationship within one Model?

后端 未结 2 1424
北荒
北荒 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 06:53

    You can store the parent FamilyMember in each FamilyMember instance like this:

    class FamilyMember(models.Model):
        user = models.OneToOneField(User)
        parent = models.ForeignKey('self', null=True)
    

    This way every FamilyMember have one parent but can be a parent of multiple FamilyMember instances. Also, for simplicity, I've made the parent field nullable.

    To save the data you can do:

    user_a1 = User(user_a1_data)
    user_a1.save()
    a1 = FamilyMember(user=user_a1, parent=None)
    a1.save()
    
    user_a2 = User(user_a2_data)
    user_a2.save()
    a2 = FamilyMember(user=user_a2, parent=a1)
    a2.save()
    

    The same goes for a3 and etc.

    Note user_a1_data and user_a2_data must be the users first_name, last_name and other fields. Did that just not to have to type all fields here.

    To retrieve the data you can do:

    a2 = FamilyMember.objects.get(pk=1)  # Assuming pk 1 is from a1.
    a2_parent = a2.parent  # That'd be a1.
    a2_parent.user.first_name # This it a1's name. Don't forget the '.user'.
    

    Note: this is untested example code just to help you get an idea of how you can organize you model relationships. The intention here is not a copy/paste ready solution.

    You can adapt this example to store child instead or in addition to parent or to

    0 讨论(0)
  • 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().

    0 讨论(0)
提交回复
热议问题