网站上的 Django ManytoMany 数据填充

Django ManytoMany data population on website

我的 Django 中有 2 个 table,其中一个是 ManytoMany 来自另一个,如下所示:

TABLE1          TABLE2           TABLE_3
ID    Item1     ID    Item2      ID     TABLE1_ID     TABLE2_ID
1     a         1     o          1      1             2
2     b         2     p          2      2             3
3     c         3     q          3      3             1

现在我尝试将 table 打印到我的索引中:

Item1      Item2
a          p
b          q
c          o

我想知道如何让它发挥作用?我被困在这里有一段时间了...请帮忙。

我尝试将 2 个列表数据用作:

TABLE1_List = TABLE1.objects.all()
TABLE2_List = TABLE2.objects.all()

在我的模板文件中,我尝试使用:

<table>
{% for t1 in TABLE1_List %}
    <tr>
       <td>{{t1.Item1}}</td>
    </tr>
{% endfor %}
</table>
<table>
{% for t2 in TABLE2_List %}
    <tr>
       <td>{{t2.Item2}}</td>
    </tr>
{% endfor %}
</table>

这将 return 2 table 对我来说,但我怎样才能将它们合并为一个 table? 请帮忙!谢谢!

如果您在两列中的项目数量相同,则类似这样的方法可能有效。 (未测试)

<table>
{% for t1 in TABLE1_List %}
{% for t2 in TABLE2_List %}
    <tr>
       <td>{{t1.Item1}}</td>
       <td>{{t2.Item2}}</td>
    </tr>
{% endfor %}
{% endfor %}    
</table>

编辑: 考虑之后,我认为您最好将两个表并排放置。或者只使用 DIV 标签等

就post我的解决方案:我在视图中将2个列表设置为元组列表,如下所示:

TABLE=list(zip(T1,T2))

并在模板中使用以下代码:

{% for t1,t2 in TABLE %}
     <tr>
          <td>t1.item1</td>
          <td>t2.item2</td>
     </tr>
{% endfor %}

谢谢。