You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django通过中间表查询时__in过滤器仅返回单条结果如何解决

你的代码存在两处核心问题,分别在视图和模板部分:

问题1:视图层查询逻辑错误

你写的Spots.objects.filter(id__in=articleSpots)中,articleSpots是中间表ArticleSpots的查询集,每个元素是中间表对象,不是关联的Spots的id。Django执行id__in匹配时,会默认取中间表对象的主键id去和Spots的id匹配,自然拿不到正确的关联spots,大概率只会返回碰巧id重合的单条数据。

问题2:模板层语法错误

  1. 你在循环外直接写了{{ spots.title }}、{{ spots.content1 }},这里的spots是查询集(多条数据的集合),不是单个Spot对象,直接调用属性不会输出正确值,还可能提前触发查询集迭代导致后续循环异常。
  2. 循环语句{% for spots in spots %}里,循环变量名和外层的查询集变量重名,会覆盖原查询集,进一步导致循环异常。

修正后的代码

views.py(两种写法可选,推荐第一种更简洁)

写法1:直接用Django跨关联关系查询,不需要单独查中间表

def article(request, slug):
    articles = get_object_or_404(Articles, slug=slug)
    # 直接通过中间表反向关联查询所有关联的Spots
    spots = Spots.objects.filter(articlespots__article=articles)
    
    context = {"spots": spots, "articles": articles}
    template_name = "articletemplate.html"
    return render(request, template_name, context)

写法2:修复你原有逻辑的写法

def article(request, slug):
    articles = get_object_or_404(Articles, slug=slug)
    # 从中间表取出所有关联的spot_id列表
    articleSpots = ArticleSpots.objects.filter(article=articles).values_list('spot_id', flat=True)    
    spots = Spots.objects.filter(id__in=articleSpots)
    
    context = {"spots": spots, "articles": articles}
    template_name = "articletemplate.html"
    return render(request, template_name, context)

模板文件修正

<!-- START MAIN -->
<main class="page">
    <p>当前文章:{{ articles.title }}</p>
    <!-- 所有关联的spot要在循环里输出 -->
    {% for spot in spots %}
    <p>
      {{ spot.title }} <br />
      {{ spot.content1 }}
    </p>
    {% endfor %}
</main>
<!-- END MAIN -->

内容的提问来源于stack exchange,提问作者haashe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:15:01