Samsquanch
Samsquanch

Reputation: 9146

How to get objects if user is in a field of another django model's many-to-many field?

I have the models:

class Project(models.Model):
    title = models.CharField(max_length=75)
    description = models.CharField(max_length=250)
...

class Node(models.Model):
    title = models.CharField(max_length=75)
    collaborators = models.ManyToManyField(User)
    project = models.ForeignKey(Project)

What I'm trying to do is get all projects where the user requesting the page is part of a node within the project.

For example: If there are projects A, B, C, D and the requesting user is a collaborator on nodes within projects A and D, projects A and D would be returned (preferably with the ability to access those nodes as well).

What is the most efficient way of doing this?

Upvotes: 0

Views: 64

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

Project.objects.filter(node__collaborators=my_user)

Upvotes: 2

Related Questions