首页 > 解决方案 > 循环遍历 django 模板中的两个查询集

问题描述

我有3个模型,

class Candidate(models.Model):
     full_name = models.CharField(max_length=255)

class CandidateProjects(models.Model):
    candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="projects")
    project_name = models.CharField(max_length=255)


class CandidateTools(models.Model):
    candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="tools")
    tool_name = models.CharField(max_length=255)


def data_view(request):
    v = Candidate.objects.get(id=1)
    template_path = 'data.html'
    context = {'v': v}
    template = get_template(template_path)
    html = template.render(context)

   data.html
   It only shows the tools data not Projects.
   {% for i in v.tools.all %}
     <tr style="width: 50%;">
        <td>
            Social Media Website with Django
        </td>
        <td>
           VS Code
        </td>
     </tr>
  {% endfor %}

在模板中,我有候选对象。我想以表格格式显示工具和项目数据,例如: 我想要的输出

谁能建议我如何仅在模板中访问这两个模型。

谢谢..

标签: pythondjangodjango-templates

解决方案


您可以尝试使用zip这样的功能,新视图看起来像

def data_view(request):
    v = Candidate.objects.get(id=1)
    template_path = 'data.html'
    context = {'v': zip(v.tools.all(), v.projects.all())}
    template = get_template(template_path)
    html = template.render(context)

data.html 看起来像

{% for i in v %}
     <tr style="width: 50%;">
        <td>
            {{i.0.tool_name}}
        </td>
        <td>
           {{i.1.project_name}}
        </td>
     </tr>
 {% endfor %}

注意:这只有在项目和工具数量相同时才能正常工作


推荐阅读