Search code examples
djangomanytomanyfield

Check if user is part of a manytomany relationship django


I have this model for a Set:

class Set(models.Model):
    name = CharField(max_length = 25)
    teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE)
    students = ManyToManyField(get_user_model(), related_name= 'set_students')

As you can see, the last field is a ManyToMany field. I need a queryset to get all the Sets that the user is part of.

How would I do this?


Solution

  • You can user reverse relation for current user user:

    user.set_students.all()
    

    Or with Set.objects by user_id:

    Set.objects.filter(students__id=user.id)