简体   繁体   中英

Many to Many query in Django

I have a many to many field like in my models below:

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')

I am trying to get all projects that each employee works on, and am stuck at how to code this in my views. What I have attempted:

def employees(request):
    if request.user.is_authenticated():
        username = str(request.user.username)

    employeeslist = Employee.objects.all().order_by('number')
    projects = Employee.projects.all()

and that obviously doesn't work. Any help would be amazing!

Just filter by employee backward relation. And don't forget to distinct() the queryset:

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

If you want to output projects per employee then you don't need to pass projects queryset to template:

{% 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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