django - 标签名称的相关帖子
问题描述
我想按标签名称显示相关帖子但是我收到错误“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]
解决方案
您可以像这样查询:
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
因为这将导致进行查询以获取评论,而使用两个单独的查询将访问数据库两次。
推荐阅读
- java - 无法解析方法“getData()”
- sql - 我有 2 列 V_DATE 和 OTP.... V_DATE 24 小时后我想设置 OTP 列 =0
- javascript - Stenciljs @Method 不工作
- java - 必须如何处理 ServerSOAPFaultException?它与处理 SOAPFaultException 有何不同?
- dart - angulardart中的两种方式绑定和监听器
- java - 获取 HashMap 中所有值的大小
> - c - C - execvp 不使用有效输入
- html - How to position an element relative to a specific background image object?
- css - 背景颜色超过背景图像 - 原因是什么?
- google-bigquery - Google 数据洞察:日期范围过滤器错误