Django: access model through another model

class Project(models.Model):
    title = models.CharField()  

class Job(models.Model):
    name = models.CharField()
    user = models.ForeignKey(User)
    project = models.ForeignKey(Project)  

I have many jobs for each project. How to get a list of all users of all project tasks?
I came up with this:

users = set()
for job in project.job_set.all():
    users.add(job.user)

Is there an easier way without an explicit loop through each job?

+3
source share
2 answers

Use the Django join syntax and start with your model User:

users = User.objects.filter(job_set__project=project).distinct()
+4
source

Alternatively, you can use the ManyToMany relation from Project to User through the Job model, which is actually a connection model:

class Project(models.Model):
   users = models.ManyToManyField(User, through='Job')
   ...

And then just do:

project.users.all()
+1
source

Source: https://habr.com/ru/post/1724832/


All Articles