Abh*_*dha 1 python django-templates
我有2张桌子:
Table1: [A-Foriegn Key, field1]
Table2: [Table1-Foriegn Key, field2]
Run Code Online (Sandbox Code Playgroud)
如果表 2 中存在项目,我想显示一个列表,其中包含表 1 字段 1 的不同值。在该列表中,我想显示与表 1 的字段 1 相对应的表 2 的所有元素。
我在尝试 :
{% for t1 in Table1 %}
Display field1 of t1
{% for t2 in Table2 %}
Display field2 of t2.
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
表格1:
????????????????????????????
? Id ? EventName ? FK ?
????????????????????????????
? 1 ? Christmas ? 56 ?
? 2 ? Black Friday ? 18 ?
????????????????????????????
Run Code Online (Sandbox Code Playgroud)
表 2:
????????????????????????????
? ID ? Image ? FK ?
????????????????????????????
? 1 ? image1_url ? 1 ?
? 2 ? image2_url ? 1 ?
? 3 ? image3_url ? 2 ?
? 4 ? image4_url ? 2 ?
????????????????????????????
Run Code Online (Sandbox Code Playgroud)
我想在列表中显示:圣诞节和黑色星期五。
在单击列表中的元素时,我想显示该特定事件的所有 url。就像点击圣诞节一样:应该显示 image1_url 和 image2_url。
我不想发出 AJAX 请求。
您可以在模板中使用外键映射来引用对象。
假设您有两个表 Table1 和 Table2,具有类似 Table1 -> Table2 的映射,Table2 中的外键字段引用 Table1,您可以执行以下操作:
你views.py会是这样的:
table1 = Table1.objects.all()
table2 = Table2.objects.all()
return render('template_name.html',{'table1':table1, 'table2':table2})
Run Code Online (Sandbox Code Playgroud)
那么你的 html 模板将是这样的:
{% for table1Instace in table1 %}
{% for table2Instance in table1Instace.table2_set.all %}
<!--Print table elements here-->
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
其中您table2Instance将是 table2 中行的对象,对应于它们在 table1 中的外键映射。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
5293 次 |
| 最近记录: |