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

Django自关联ForeignKey的related_name失效,模板无法获取反向子机构列表

修复方案

1. 修正视图代码

你使用的DetailView本身支持自动获取当前单条机构数据,不需要冗余的自定义查询,优化后代码如下:

# views.py
class InstitutionDetail(DetailView):
    model = Institution
    # 预加载子机构数据,减少数据库查询次数
    queryset = Institution.objects.prefetch_related('child')

DetailView会自动将当前访问的机构对象传入模板,变量名为institution。

如果你要保留自定义get方法的写法,修正后如下:

# views.py
class InstitutionDetail(DetailView):
    model = Institution

    def get(self, request, *args, **kwargs):
        # 预加载子机构后查询当前机构
        current_institution = get_object_or_404(Institution.objects.prefetch_related('child'), pk=kwargs['pk'])
        context = {'institution': current_institution}
        return render(request, 'stakeholders/institution_detail.html', context)

2. 修正模板代码

你已经自定义了反向关联的related_name="child",直接遍历该关联的查询集即可拿到所有子机构:

<p><b>Child institution: </b></p>
<ul>
{% for child in institution.child.all %}
    <li>
        <a href="{% url 'stakeholders:institution_detail' child.id %}">
            {{ child.name }}
        </a>
    </li>
{% empty %}
    <li>暂无关联子机构</li>
{% endfor %}
</ul>

之前的错误原因

  • 自定义related_name="child"后,反向关联的属性名是child,不是默认的parent_institution_set,用后者取值会返回空
  • 反向关联返回的是多个子机构组成的查询集,不是单个对象,不能直接写institution.child.name获取属性,必须遍历查询集
  • 原视图中institutions_child的查询逻辑完全错误,查询的是全局所有无父机构的机构,和当前访问的父机构没有关联,属于冗余无效查询
  • 原视图把单个当前机构对象命名为复数的institutions,命名混乱导致模板取值容易出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:15:03