django用户关注者从数据库中检索

时间:2017-10-18 18:17:04

标签: python django

我有一个用户跟随系统的应用程序,我已经能够实现,但我尝试检索单个用户关注者和跟随但我无法得到它。以下是我的代码

View.py

def following(request):
    query = Contact.objects.filter(request.user.following)
    context = {
        'query': query
        }
    template = 'following.html'
    return render(request, template, context)

Models.py

class Contact(models.Model):
    user_from = models.ForeignKey(User,related_name='rel_from_set')
    user_to = models.ForeignKey(User,related_name='rel_to_set')
    created = models.DateTimeField(auto_now_add=True,db_index=True)

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return '{} follows {}'.format(self.user_from,self.user_to)

User.add_to_class('following',models.ManyToManyField('self', through=Contact,related_name='followers', symmetrical=False))

模板

{% load staticfiles %}
{% block content %}
<h2>following</h2>
<div id="action-list">

<h1>{{ results.get_full_name }}</h1>
</div>
{% endblock %}

将根据要求添加其他代码。

1 个答案:

答案 0 :(得分:0)

这可以通过两种方式解决。首先:您的过滤器不正确:

def following(request):
    query = Contact.objects.filter(user_from=request.user)
    context = {
        'query': query
        }
    template = 'following.html'
    return render(request, template, context)

使用related_name

的反向关系的另一种解决方案
def following(request):
    query = request.user.rel_from_set.all()
    context = {
        'query': query
        }
    template = 'following.html'
    return render(request, template, context)

当然,与user_to的{​​{1}}字段类似。

编辑:您的模板没有使用您在视图Contact中定义的正确上下文变量。所以你需要稍微调整一下:

following