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

如何在Django ListView中展示work_allocation模型的所有关联子字段

视图修改(views.py)

首先优化get_task_list类视图,预加载外键关联数据,避免重复查询数据库,同时可自定义上下文变量和模板路径:

# 原有导入保留
class get_task_list(ListView):
    model = work_allocation
    # 自定义上下文变量名,模板中更易识别
    context_object_name = "task_list"
    # 可自定义模板路径,不填则默认查找路径为:<你的app名>/work_allocation_list.html
    template_name = "tasks/task_list.html"

    def get_queryset(self):
        # 预加载所有外键关联数据,解决N+1查询问题
        queryset = super().get_queryset().select_related(
            "Assignee_name", "Status_code", "priority"
        )
        return queryset

模板编写

在你指定的模板路径下新建对应模板文件,示例内容如下:

<h1>任务列表</h1>
<table>
  <thead>
    <tr>
      <th>活动名称</th>
      <th>JIRA单号</th>
      <th>负责人</th>
      <th>状态</th>
      <th>优先级</th>
      <th>计划开始时间</th>
      <th>计划结束时间</th>
    </tr>
  </thead>
  <tbody>
    {% for task in task_list %}
    <tr>
      <td>{{ task.activity_name }}</td>
      <td>{{ task.JIRA_tkt }}</td>
      <!-- 外键字段直接通过关联属性取对应字段即可 -->
      <td>{{ task.Assignee_name.emp_name }}</td>
      <td>{{ task.Status_code.Types }}</td>
      <td>{{ task.priority.priority }}</td>
      <td>{{ task.Planned_start_date }}</td>
      <td>{{ task.Planned_end_date }}</td>
    </tr>
    {% empty %}
    <tr>
      <td colspan="7">暂无任务数据</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

额外注意事项

  1. 你当前work_allocation模型中所有日期字段都设置了auto_now_add=True,该属性会让字段在数据创建时自动赋值为当前时间,且后续无法修改,会导致你表单提交的自定义日期无法存入数据库。如果需要手动填写日期,请删除这些字段的auto_now_add=True配置。
  2. 建议遵循Django编码规范:模型类名使用大驼峰命名(如work_allocation改为WorkAllocation),字段名统一使用小写下划线命名(如Assignee_name改为assignee_name),方便后续维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:45:02