[Python] How to get friends of friends (mutual friends) - Django

Discussão em 'Python' iniciado por Stack, Julho 4, 2025.

  1. Stack

    Stack Membro Participativo

    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)

    Continue reading...

Compartilhe esta Página