python - 循环遍历 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 %}
在模板中,我有候选对象。我想以表格格式显示工具和项目数据,例如:
谁能建议我如何仅在模板中访问这两个模型。
谢谢..
解决方案
您可以尝试使用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 %}
注意:这只有在项目和工具数量相同时才能正常工作
推荐阅读
- dialogflow-es - 在 Dialogflow Essentials 中重新提示用户输入
- python - 凭据过期时如何重新发送 cognito 邀请
- ansible - 如何包含角色(vars)目录中的变量?
- excel - 在 Excel 中调用时返回运行时错误 '438 的 Word 函数
- ionic-framework - 无法添加名称为“googleServices”的扩展程序,因为已使用该名称注册了一个扩展程序。- 离子电容器
- android - 将 Android 项目转移到 Git 私有服务器
- angular - 使用 Angular 和 JWT 令牌持续登录
- odk - ODK - 根据选择显示值
- c# - 使用 BsonClassMap 时获取 MongoDB 中插入文档的 _id?
- node.js - 无法接收从 redis 服务器内部触发的 socketio 发射