我该如何解决查询对象错误-ValueError:无法查询“ mayur”:

我正在尝试在可用模块中访问我的关注者,我可以获取计数(例如关注者数量和关注者数量),但无法获取关注者列表以查看我的关注者。需要建议。


我的module.py文件:


from django.db import models


class FollowerFollowing(models.Model):

        user_from = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='rel_from_set')

        user_to = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, 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('User', through=FollowerFollowing, related_name='followers', symmetrical=False))

我的views.py文件:


def follower(request):

    print(request)

    if request.session['user_id']:

        query = FollowerFollowing.objects.filter(user_from=request.user)

        print(query)

        context = {

            'query': query

            }

        return render(request, 'Instagram_app/following.html', context)

    else:

        pass

    return HttpResponse("No user logged in")

follower.html(模板)


{% extends 'Instagram_app/home.html'%}

{% block content %}

    <h2>following</h2>

    <div id="action-list">

        {% for result in query %}

            <h1>{{ result }}</h1>

        {% endfor %}

    </div>

{% endblock %}

控制台错误是:


(value, opts.object_name))

ValueError: Cannot query "mayur": Must be "User" instance.

[20/Jun/2018 11:45:27] "GET /Instagram_app/follower HTTP/1.1" 500 105165

需要解决此问题的建议。谢谢


犯罪嫌疑人X
浏览 160回答 2
2回答

忽然笑

尝试更改此部分:(user_from=request.user)为此:(user_from=User.objects.get(username=request.user))您user_from必须是User模型实例,而不是简单的用户名。

qq_笑_17

尝试根据登录的用户会话更改代码以显示以下列表从:query&nbsp;=&nbsp;FollowerFollowing.objects.filter(user_from=request.user)至:query&nbsp;=&nbsp;FollowerFollowing.objects.filter(user_from=request.session['user_id'])因为request.user它为您提供了所有用户的单个和最先登录用户的以下列表。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python