在django模板中通过两个queryset循环

iyzzxitl  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(432)

我有三个模型,

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 %}

在模板中,我有候选对象。我希望以表格格式显示工具和项目数据,如:

任何人都可以建议我如何仅在模板中访问这两个模型。
谢谢

db2dz4w8

db2dz4w81#

你可以试试看 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)

html看起来像

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

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

相关问题