wtreston
wtreston

Reputation: 1061

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?

Upvotes: 2

Views: 3645

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

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)

Upvotes: 9

Related Questions