Karna
Karna

Reputation: 148

Filtering Django query filtering

I'm doing some querying currently and I was wondering if I would be able to query something from these 3 models where the return would give me all the projects the users are working on. I know about the basic filtering however thats not really enough in this case, how would one go about querying through 2 foreign keys.

class User(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField()

class ProjectUser(models.Model):
    project = models.ForeignKey("Project", on_delete=models.CASCADE)
    user = models.ForeignKey("User", on_delete=models.CASCADE)
    is_lead = models.BooleanField(default=False)

    class Meta:
        unique_together = (("project", "user"),)

class Project(models.Model):
    name = models.CharField(max_length=255)
    client = models.CharField(max_length=255)
    complete = models.BooleanField(default=False)

Upvotes: 1

Views: 45

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

You can obtain the Projects a user is working on with:

Project.objects.filter(
    projectuser__user=user
)

The double underscores are used to look "through" relations. Furthermore the default related_query_name=… parameter [Django-doc] is, if not specified, the name of the model in lowercase.

Upvotes: 2

Related Questions