首页 > 解决方案 > 标签名称的相关帖子

问题描述

我想按标签名称显示相关帖子但是我收到错误“get() returned more than one Tag -- it returned 2!"

def post_detail(request,slug):
        post=get_object_or_404(Post,slug=slug)
        comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date')
        comment_count=len(Comment.objects.filter(post=post, statusc=2))
        tag=get_object_or_404(Tag,post=post)
        related_item=Post.objects.filter(tag__tag_name__icontains=tag.tag_name,status=2).order_by('-created_date').distinct()[:3]

标签: djangodjango-views

解决方案


您可以像这样查询:

def post_detail(request,slug):
    post=get_object_or_404(Post,slug=slug)
    comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date')
    comment_count=len(comments)

    related_items = Post.objects.filter(
        tag__post=post
    ).order_by('-created_date').distinct()[:3]
    # ...

或者,如果您想排除当前帖子:

def post_detail(request,slug):
    post=get_object_or_404(Post,slug=slug)
    comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date')
    comment_count=len(comments)

    related_items = Post.objects.exclude(pk=post.pk).filter(
        tag__post=pos
    ).order_by('-created_date').distinct()[:3]
    # ...

最好在 上执行 a len(..)comments因为这将导致进行查询以获取评论,而使用两个单独的查询将访问数据库两次。


推荐阅读