繁体   English   中英

如何在 django 模板中反向查找 m2m 字段

[英]How to do a reverse look up of m2m field within django template

您好,我一直在尝试进行反向 m2m 查询和计数,但没有这样做。 其他帖子建议的方法似乎不起作用,这是我目前的代码。

这是我的 HTML 中的相关部分:

    <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 CustomerView(ListView):


 model = CustomerInformation
  template_name = 'rnd/customers_all.html'
  context_object_name = 'customers'
  def get_context_data(self, **kwargs):
    context = super(CustomerView, self).get_context_data(**kwargs)
    context['customers'] = CustomerInformation.objects.all()
    return context

这是我的模型:

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 字段,以显示与该公司关联的项目数量的相关计数,但结果不显示任何内容而不会引发任何错误。 任何帮助将不胜感激!

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

可以直接这样调用

我想你想做:

<td>{{customer.salesproject_set.all.count}}</td>

代替:

{% for project in customer.salesProject_set.all %}
    <td>{{project.count}}</td>
{%endfor%}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM