【问题标题】:ValueError at /index.............The QuerySet value for an exact lookup must be limited to one result using slicingValueError at /index.............精确查找的 QuerySet 值必须使用切片限制为一个结果
【发布时间】:2022-01-12 05:52:39
【问题描述】:

我正在 django 中构建一个社交媒体网站。当我尝试在索引页面中列出所有 cmets 时,我收到了这个错误,精确查找的 QuerySet 值必须限制为使用切片的一个结果。

这种情况我该怎么办

views.py....

def index(request):
if request.user.is_authenticated:
    allPost = Post.objects.all().order_by('-created_on').filter(creater = request.user)
    allBlog = Blogpost.objects.all()
    comments = PostComment.objects.filter(post=allPost)
    context = {'allPost' : allPost, 'allBlog' : allBlog, 'comments' : comments}
    return render(request, 'index.html', context)
    
else:
    return render(request, "signoption.html")

models.py....

class PostComment(models.Model):

    sno = models.AutoField(primary_key=True)

    comment = models.TextField()

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)

    created_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.sno) + '.....comment By.....' + str(self.user)

index.html....

{% for comment in comments %}
<div class="comment">
    <div class="comment-user">
        <div class="comment-usr-dp">
            <img src="{%static 'img/profile/profile.png'%}" alt="">
        </div>
    </div>
    <div class="comments-usr-usrname">
        <b><h1>{{comment.user.username}}</h1></b>
    </div>
    <div class="comment-text">
        <h1>{{comment.comment}}</h1>
     </div>
     <div class="comment-time">
        <h1>{{comment.created_on}}</h1>
     </div>
</div>
{%endfor%}

【问题讨论】:

    标签: python html django


    【解决方案1】:

    comments = PostComment.objects.filter(post=allPost) 更新为

    cmets = PostComment.objects.filter(post__in=allPost)

    注意:post__in 在过滤器中。

    【讨论】:

    • 我试过这样做............ cmets = PostComment.objects.filter(post_in=allPost)............但现在是给我这个错误............无法将关键字“post_in”解析为字段。选项有:comment、created_on、parent、parent_id、post、post_id、postcomment、sno、user、user_id
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2019-05-26
    • 2019-10-02
    • 2019-11-10
    • 2021-07-20
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多