简体   繁体   English

django:通过view.py中的向后关系而不是模板来检索对象

[英]django: Retrieve object via backwards relationship in view.py, not template

Just starting out to program in python and I'm having the following issue. 刚开始用python编程,我遇到了以下问题。 I have a template that shows details on a supplier, each supplier has employees and on the template page, I want to show the names of the employees. 我有一个显示供应商详细信息的模板,每个供应商都有员工,并且在模板页面上,我想显示员工的姓名。 I know how to do it in the template, but how do you do that in the view? 我知道如何在模板中执行此操作,但是如何在视图中执行此操作?

MODELS: 楷模:

class Supplier(models.Model):
    co_name = models.CharField(max_length=100)
    co_city = models.CharField(max_length=100)
    co_state = models.CharField(max_length=2)

class Supplieremployees(models.Model):
    supplier = models.ForeignKey(supplier)
    expe_fname = models.CharField(max_length=50)

VIEWS: 意见:

def supplier_detail(request, supplier_id):
    s = get_object_or_404(Supplier, pk=supplier_id)
    **test = s.supplieremployees_set.all()**
    return render_to_response('suppliersdb/supplier_detail.html', {'supplier': s})

TEMPLATE: 模板:

...i dont want to use this way, how do i translate this into the view?
{% for supplieremployees in supplier.supplieremployees_set.all %}
    <li>IT Focal: {{ supplieremployees.expe_fname }}</li>
{% endfor %}

**TEST: {{ test.expe_fname }}**

nothing shows up for {{ test.expe_fname }} {{test.expe_fname}}没有任何显示

A Supplier object will have a supplieremployees_set property that can access the reverse relation: 一个Supplier对象将有一个supplieremployees_set可以访问反向关系属性:

employees = s.supplieremployees_set

You can also supply a related_name argument to the ForeignKey and use that: 您还可以为ForeignKey提供related_name参数,并使用该参数:

class Supplieremployees(models.Model):
    supplier = models.ForeignKey(Supplier, related_name='employees')

employees = s.employees
def supplier_detail(request, supplier_id):
    s = get_object_or_404(Supplier, pk=supplier_id)
    for employee in s.supplieremployees_set.all():
        print employee.expe_fname
    return render_to_response('suppliersdb/supplier_detail.html', {'supplier': s})

from the docs 从文档

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

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