How to get friends of friends (mutual friends) - Django
I have been able to get the list of all users and also implement sent friend request (following/follower). Now, how do I get mutual friends(following/followers)? For example; if both user have an existing friend in common.
Below code is what I have tried, but not displaying mutual friends. What am I doing wrong and how can I get it done correctly?
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
profile_pic = models.ImageField(upload_to='UploadedProfilePicture/', default="ProfileAvatar/avatar.png", blank=True)
following = models.ManyToManyField(
'Profile', # Refers to the User model itself
symmetrical=False, # If A follows B, B doesn't automatically follow A
related_name='followers', # Reverse relationship: get followers of a user
blank=True,
)
def FollowingView(request):
page_title = "Following"
# All users following posts
posts = Post.objects.filter(
Q(poster_profile=request.user)|
Q(poster_profile__profile__followers__user=request.user)).order_by("?").distinct()
# All account users
profile_users = Profile.objects.exclude(
Q(user=request.user))
# Mutual Followers
all_following = request.user.profile.following.values_list('pk', flat=True)
mutual_followers = Profile.objects.filter(pk__in=all_following)
You can get the followers of followers of a user with:
friends_of_friends = Profile.objects.filter(followers__followers__user=request.user)
or for mutual friends between request.user
and a user C:
friends_of_friends = Profile.objects.filter(
followers__user=request.user
).filter(
followers__user=C
)
If you want to do this for all Profile
s, you can work with a Prefetch
object:
my_profiles = Profile.objects.prefetch_related(
Prefetch(
'following',
Profile.objects.filter(followers__user=request.user),
to_attr='friends_in_common'
),
)
The Profile
s in my_profiles
will have an extra attribute .friends_in_common
with a collection of Profile
s in common with request.user
.