如何获得朋友的朋友数 [英] How to get count of friends of friends

查看:64
本文介绍了如何获得朋友的朋友数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个类似于instagram的网站,用户可以在其中关注朋友,我已经能够实现关注朋友,并且还可以显示朋友的朋友(共同的朋友).我无法得到朋友的朋友的数目;这就是我尝试过的:

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:

型号:

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)

视图:

@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(...)

模板:

{% 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 %}

推荐答案

您需要使用 friends_of_friend.count 来获取当前用户的朋友数.如果您希望每个朋友的朋友计数,请使用 {{friend.friends.count}} .

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 }}.

老实说,模板中不需要那么多上下文.您可以从模板中的 {{user}} 属性访问它们.例如:

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 %}

这篇关于如何获得朋友的朋友数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆