DJANGO:在模板中显示多对多的附加字段
Posted
技术标签:
【中文标题】DJANGO:在模板中显示多对多的附加字段【英文标题】:DJANGO: Showing many-to-many additional fields in template 【发布时间】:2012-03-29 09:36:58 【问题描述】:我有以下情况:一个项目可以属于多个部门,员工被分配到多个项目的角色。如何在模板中显示角色字段? 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)
模板
<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 %
【问题讨论】:
你在模板的一个地方有employees
,在另一个地方有employee
。
【参考方案1】:
迭代“通过”模型而不是目标模型:
% for membership in projects.membership_set.all %
<li>
membership.employee | membership.role
</li>
% endfor %
【讨论】:
我通过使用 % for employees in projects.membership_set.all % 而不是使用 % for employees in projects.members.all % 解决了这个问题。不知道有什么区别,但它有效!以上是关于DJANGO:在模板中显示多对多的附加字段的主要内容,如果未能解决你的问题,请参考以下文章