How to get count of friends of friends

家住魔仙堡 提交于 2021-02-11 15:54:55

问题


i am building a website like instagram where users can follow friends, i have been able to implement follow friend and also displaying friends of friends (mutual friend). I was not able to get the count of friends of friends; this is what i tried:

Model:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
    friends = models.ManyToManyField('Profile', related_name="my_friends",blank=True)

view:

@login_required
def profile_user_view(request, username):
    #Friend of Friends
    p = Profile.objects.filter(user__username=username).order_by('-id')
    all_friends = request.user.profile.friends.values_list('pk', flat=True)
    friends_of_friend = Profile.objects.filter(pk__in=all_friends)    
context = {
    'profile_img': p,
    'friends_of_friend': friends_of_friend,
}
return render(...)

Template:

{% for data in profile_img %}
{% for friend in friends_of_friend %}
{% if friend in data.friends.all %}
<li>
<a href="{% url 'site:profile-view' friend.user.username %}" class="dark-grey-text">
   <b>{{ friend.user.username|lower }}</b>
</a>
</li>
<li>
    {{ friend.count }} #This is not showing the count of friends of friends, when i use length it displays '0 0' instead of '2' (mutual friends)
</li>
{% endif %}
{% endfor %}
{% endfor %}

回答1:


You need to use friends_of_friend.count to get count of current user's friends. If you want every friend's friend count then use {{ friend.friends.count }}.

Honestly, you do not need this much context in template. You can access them all from {{ user }} attribute in template. For example:

{% for friend in user.friends.all %}
  Username {{ friend.user.username | lower }}
  Count {{ friend.friends.count }}
{% endfor %}


来源:https://stackoverflow.com/questions/62425657/how-to-get-count-of-friends-of-friends

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!