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