Py学习  »  Django

通过Django模板文件反向查询

Sean H • 5 年前 • 1893 次点击  

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)

公司详细信息.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页面上。如何正确反向查询以显示该公司下的所有联系人?

提前谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51671
 
1893 次点击  
文章 [ 1 ]  |  最新文章 5 年前