Django 中的多对多查询



我有一个多对多的领域,就像下面的模型一样:

class Project(models.Model):
 name = models.CharField(verbose_name="Project Name", max_length=1000, blank = True, null = True)
 number = models.IntegerField(verbose_name = "Project Number", blank =False ,null=False)
class Employee(models.Model):
     name = models.CharField(verbose_name="Full Name", max_length=1000, blank = True, null = True)
     number = models.IntegerField(verbose_name = "Number", blank = True ,null = True)
     salary = models.IntegerField(verbose_name = "Salary", blank =True ,null=True)
     departmentnum = models.IntegerField(verbose_name = "Department Number", blank = False ,null = False)
     projects = models.ManyToManyField('Project')

正在尝试获取每个员工从事的所有项目,并且卡在如何在我的观点中对此进行编码。我尝试过什么:

def employees(request):
    if request.user.is_authenticated():
        username = str(request.user.username)
    employeeslist = Employee.objects.all().order_by('number')
    projects = Employee.projects.all()

这显然是行不通的。任何帮助都会很棒!

只需按向后关系过滤employee即可。 并且不要忘记distinct()查询集:

projects = Project.objects.distinct().filter(employee__in=employeeslist)

如果要为每个员工输出项目,则无需将查询集传递给模板projects

{% for employee in employee_list %}
    <h1>{{ employee.name }}</h1>
    <ul>
    {% for project in employee.projects.all %}
        <li>{{ project.name }}</li>
    {% endfor %}
    </ul>
{% endfor %}

如果你想得到多对多的值,你可以写employeeslist.projects_set.all()

相关内容

  • 没有找到相关文章

最新更新