我有以下情况:项目可以属于多个部门,员工被分配到多个项目的角色。如何在模板中显示角色字段? employees.role显示空白......
模型
class Projects(models.Model):
name = models.CharField(max_length=20)
class Department(models.Model):
name = models.CharField(max_length=20)
class Employees(models.Model):
fname = models.CharField(max_length=15)
class Departmentprojects(models.Model):
department = models.ForeignKey(Department)
projects = models.ForeignKey(Projects)
members = models.ManyToManyField(Employee, through='Membership')
class Membership(models.Model):
departmentprojects = models.ForeignKey(Departmentprojects)
employee = models.ForeignKey(Employee)
role = models.CharField(max_length=20) #i want to show this field in a template
查看
def department_detail(request, company_id):
department = get_object_or_404(Department, pk=department_id)
return render_to_response('test/detail.html', {'department': department})
TEMPLATE
<h1>{{ department.name }}</h1>
{% for projects in department.departmentprojects_set.all %}
<h2>{{ projects.projects }}</h2>
<ul>
{% for employees in projects.members.all %}
<li>{{ employee }} | {{ employee.role }}</li>
{% endfor %}
</ul>
{% endfor %}
答案 0 :(得分:4)
迭代“直通”模型而不是目标模型:
{% for membership in projects.membership_set.all %}
<li>
{{ membership.employee }} | {{ membership.role }}
</li>
{% endfor %}