Django模板嵌套for循环展示两关联模型数据匹配异常
问题根源
代码存在两个核心逻辑错误,导致数据无法按外键关系匹配:
- 视图逻辑混淆:当前贴出的是详情页视图逻辑,却承担列表页渲染工作:用同一个主键值同时查询单条Section和单条SectionInfo数据,既没有查询全量分区列表,也没有按外键关系做数据关联。
- 模板循环逻辑错误:内层循环直接遍历全量SectionInfo集合,没有和外层循环的当前分区做绑定,且详情链接传入的是分区ID而非具体信息ID,导致所有分区下的链接完全一致、内容重复。
修正方案
1. 模型可选优化(推荐)
给SectionInfo模型的外键字段添加related_name参数,方便后续反向查询关联数据,修改Models.py对应字段:
class SectionInfo(models.Model): # 新增related_name参数,值可自定义 section_name = models.ForeignKey(Section, on_delete=models.CASCADE, related_name="info_items") detail = models.CharField(max_length=50) text = models.TextField(max_length=2000) date_created = models.DateField('Date created', auto_now_add=True) date_updated = models.DateField('Date updated', auto_now=True)
如果不添加该参数,反向查询时使用Django默认的模型名_set格式(即section.sectioninfo_set)也可正常取值。
2. 修正视图逻辑
区分列表页和详情页的视图职责,不要混用查询逻辑:
# 分区列表页视图(对应渲染所有分区+关联信息的页面) def section_list(request): # 仅需查询全量分区即可,关联的SectionInfo可通过外键反向获取 all_sections = Section.objects.all() context = { "sections": all_sections } return render(request, 'manufacturing/section_list.html', context) # 分区信息详情页视图(修正原逻辑错误,仅查询对应SectionInfo实例) def section_info_detail(request, pk): current_info = get_object_or_404(SectionInfo, id=pk) context = { "info": current_info } return render(request, 'manufacturing/section_info_detail.html', context)
记得在urls.py中给新增的section_list视图配置对应路由。
3. 修正模板循环逻辑
内层循环直接遍历当前分区下关联的SectionInfo数据,不要遍历全量信息集合,同时修正详情链接的传参:
{% extends "base.html" %} {% load bootstrap5 %} {% load crispy_forms_tags %} {% load static %} {% block content %} {% for section in sections %} <h4>{{ section.name }}</h4> <div class="row"> <div class="col-sm-4"> <div class="card"> <div class="card-body"> {# 若未加related_name,把info_items替换为sectioninfo_set #} {% for info in section.info_items.all %} <div class="py-2 border-bottom"> <p class="mb-1">{{ info.detail }}</p> <p class="text-muted small mb-1">创建时间:{{ info.date_created|date:"Y-m-d" }}</p> {# 链接传入当前SectionInfo的id,而非分区id #} <a href="{% url 'manufacturing:section_info_detail' info.id %}">查看详情</a> </div> {% empty %} <p class="text-muted mb-0">该分区暂无录入信息</p> {% endfor %} </div> </div> </div> </div> {% endfor %} {% endblock content %}
修正说明
- 外键反向查询会自动按关联关系过滤数据,只会返回属于当前分区的SectionInfo内容,不会出现跨分区数据重复展示的问题
- 详情链接传入每条SectionInfo自身的主键,点击后会跳转到对应信息的详情页,不会出现所有链接地址一致的问题
- 新增
empty分支处理分区无关联信息的场景,避免卡片内空白
内容的提问来源于stack exchange,提问作者Alec
相关产品推荐
相关产品推荐

