Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get friends of friends - Django

Tags:

python

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?

enter image description here

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)
like image 579
user30880337 Avatar asked Dec 19 '25 15:12

user30880337


1 Answers

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 Profiles, 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 Profiles in my_profiles will have an extra attribute .friends_in_common with a collection of Profiles in common with request.user.

So we can render this with:

<ul>
{% for profile in my_profiles %}
  <li><b>{{ profile.user.username }}</b>
  <ul>
  {% for common in profile.friends_in_common %}
    <li>{{ common.user.username }}</li>
  {% endfor %}
  </ul>
  </li>
{% endfor %}
</ul>
like image 147
Willem Van Onsem Avatar answered Dec 21 '25 07:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!