RoyKeane94
RoyKeane94

Reputation: 65

How to access many-to-many field associated with specific model id in Django?

For a specific project id, I would like to be able to access all users associated with the project.

models.py is below:

class IndividualProject(models.Model):
    project = models.CharField(
        max_length = 64
        )

    group = models.ForeignKey(
        Group,
        on_delete=models.CASCADE,
        related_name = "project_group",
        blank=True,
        null=True, 
    )

    user = models.ManyToManyField(
        UserProfile,
        blank = True,
    )

    def __str__(self):
        return f"Project {self.project}"

If I do IndividualProject.objects.get(id = 1), I would like to be able to see all of the users associated with that project.

I can find all projects associated with a specific user per the below:

test = UserProfile.objects.get(id = 1)

test.individualproject_set.all()

Is there a way to do the above but using a specific project?

Thank you!

Upvotes: 0

Views: 31

Answers (2)

Simple as:

IndividualProject.objects.get(id = 1).user.all()

Upvotes: 1

AKX
AKX

Reputation: 169407

Just look at the forward relation on the many-to-many field:

project = IndividualProject.objects.get(id=1)
print(project.user.all())  # queryset of Users

You might want to consider renaming the field to users, though, since it refers to multiple users, not just one.

Upvotes: 1

Related Questions