标签名称相关文章

时间:2019-07-03 09:12:20

标签: django django-views

我想按标签名称显示相关帖子,但是我遇到了错误“ 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]

2 个答案:

答案 0 :(得分:2)

根据documentationget()用于检索1个项目。如果有多个项目,则在单个Post中可能使用了多个标签,它将引发错误。

因此,您可以像这样更改它:

 tags=Tag.objects.filter(post=post)
 related_item=Post.objects.filter(tag__in=tags,status=2).order_by('-created_date').distinct()[:3]

答案 1 :(得分:1)

您可以像这样查询:

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]
    # ...

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