Python 如何在django模板中反向查找m2m字段
你好,我一直在尝试做一个反向m2m查询和计数,但失败了。其他帖子建议的方法似乎不起作用,这是我目前的代码 这是我的HTML中的相关位:Python 如何在django模板中反向查找m2m字段,python,django,django-models,django-templates,many-to-many,Python,Django,Django Models,Django Templates,Many To Many,你好,我一直在尝试做一个反向m2m查询和计数,但失败了。其他帖子建议的方法似乎不起作用,这是我目前的代码 这是我的HTML中的相关位: <table id='myTable' class="display ui celled table" style="width:100%"> <thead> <tr> <th>ID</th>
<table id='myTable' class="display ui celled table" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Company</th>
<th>Company Address</th>
<th>Telephone</th>
<th>Total Projects</th>
</tr>
</thead>
{% for customer in customers %}
<tr>
<td>{{ customer.customer_id }}</td>
<td><a href="{% url 'customer-profile' customer.customer_id %}" class='btn w3-teal'>{{ customer.customer_name }}</a></td>
<td>{{ customer.address }}</td>
<td>{{ customer.telephone_number}}</td>
{% for project in customer.salesProject_set.all %}
<td>{{project.count}}</td>
{%endfor%}
</tr>
{% endfor %}
</table>
</div>
这是我的模型:
class SalesProject(models.Model):
customer_information = models.ManyToManyField('CustomerInformation')
class CustomerInformation(models.Model):
customer_id = models.AutoField(primary_key=True)
customer_name = models.CharField(max_length=100, default='Lee Ji Eun')
telephone_number = models.CharField(max_length=100)
我打算访问模板中的m2m字段,以便显示与该公司相关的项目数量的相关计数,但结果不会显示任何内容而不会抛出任何错误。任何帮助都将不胜感激 {customers%中客户的%
{% for customer in customers %}
<tr>
<td>{{ customer.customer_id }}</td>
<td><a href="{% url 'customer-profile' customer.customer_id %}" class='btn w3-teal'>{{ customer.customer_name }}</a></td>
<td>{{ customer.address }}</td>
<td>{{ customer.telephone_number}}</td>
{% for project in customer.salesproject.customer_information.all %}
<td>{{project.count}}</td>
{%endfor%}
</tr>
{% endfor %}
{{customer.customer\u id}
{{customer.address}
{{客户电话号码}
{customer.salesproject.customer_information.all%}
{{project.count}
{%endfor%}
{%endfor%}
您可以通过这种方式直接呼叫我想您应该做:
<td>{{customer.salesproject_set.all.count}}</td>
{{customer.salesproject_set.all.count}
而不是:
{% for project in customer.salesProject_set.all %}
<td>{{project.count}}</td>
{%endfor%}
{%for customer.salesProject_set.all%}
{{project.count}
{%endfor%}
这回答了你的问题吗?谢谢,是的,它回答了我的问题,很抱歉回复太晚,你绝对是个救命恩人!
{% for project in customer.salesProject_set.all %}
<td>{{project.count}}</td>
{%endfor%}