通过Django模板文件进行反向查询

时间:2019-12-23 01:35:38

标签: django django-models django-templates django-views

models.py文件

class Company(models.Model):
    name = models.CharField(max_length=30)
    def __str__(self):
        return self.name



class Contact(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    def __str__(self):
        return self.first_name

views.py文件

class company_detail(DetailView):
    def get(self, request, *args, **kwargs):
        company = get_object_or_404(Company, pk=kwargs['pk'])
        context = {'company': company}
        return render(request, 'crm/company_detail.html', context)

company_detail.html文件

{% extends 'base.html' %}
{% block content %}
<div id="container">
    <ul>
        <li>{{company.name}}</li>
    </ul>


    {% for company in object_list %}
         {{ company.name }}
         {% for Contact in company.contact_set.all %}
             {{Contact.first_name}}
         {% empty %}
            <!-- no entries -->
         {% endfor %}
    {% endfor %}

</div>



{% endblock content %}

我试图让该公司下的联系人显示在company_detail.html页面上。如何正确反向查询以显示该公司下的所有联系人?

预先感谢

1 个答案:

答案 0 :(得分:0)

object_list的上下文中没有DetailView,只有对象。您需要删除模板中object_list上的for循环

 {% for contact in company.contact_set.all %}
     {{ contact.first_name }}
 {% empty %}
    <!-- no entries -->
 {% endfor %}