thedeepfield
thedeepfield

Reputation: 6196

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. 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 }}

Upvotes: 0

Views: 531

Answers (2)

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53998

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

Upvotes: 1

mipadi
mipadi

Reputation: 411350

A Supplier object will have a supplieremployees_set property that can access the reverse relation:

employees = s.supplieremployees_set

You can also supply a related_name argument to the ForeignKey and use that:

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

employees = s.employees

Upvotes: 1

Related Questions