What is the best way to model user friendships for a social networking site?
Possible states:
- no friendship
- FriendRequest from A to B, B must be confirmed (this is asymmetric)
- A and B are friends (this is symmetrical)
Now itβs hard to choose the right model.
My friends are part of my profile
quite obviously, A.profile.friends is a many, many relation to other users.
- no friendship: B is not in A.friends and A is not in B.friends
- A asks for friendship with B: B in A.friends
- Friends: B in A.friends and A in B.friends
but it seems pretty unclean to combine a friend with a friendrequest relationship. and without this merge, the data is redundant, because then "A in B.friends, not B in A.friends" will be an undefined state.
Friend-Lookup: A.friends.filter (friends__contains = B) # complex db level search, not intuitive for coders
Separate tables
FriendRequest is quite obvious, the class with the requester and request_user, the choice is also pretty obvious.
Friend model will not be very pleasant, because it will have person1 and person2 as fields, and for all searches it is necessary to choose friends with person1 = A and person2 = B OR person1 = B and person2 = A
Friend-Lookup: Friend.objects.filter (person1 = A) union Friend.objects.filter (person2 = A) #unclean with the need to combine the two sets
Separate a lot of 2 tables
Another option would be the Friend model with a friends field, which is a multi-headed field that connects exactly two people. Then the selection corresponds to one of the persons in the friends field, and then simply returns a model where person B can be issued by subtracting A from the set of friends. But that would be superfluous, because none of the acquaintances would have more than two people.
Friend-Lookup: Friendship.objects.filter (persons__contains = A) # queries two tables
So, what do you consider the cleanest and most intuitive solution to maintaining a friendship? Are there any common patterns on how to do this?