Home > Software engineering >  How to access many-to-many field associated with specific model id in Django?
How to access many-to-many field associated with specific model id in Django?

Time:08-04

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!

CodePudding user response:

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.

CodePudding user response:

Simple as:

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