Skip to content
Advertisement

Flitering django queryset based on ManyToManyField

In my Request model, there is a field requested_to which is a ManyToManyField

requested_to = models.ManyToManyField(OrganizationUser)

I want to filter queryset of Request model where a organization_user is not in requested_to

Advertisement

Answer

You can filter with:

Request.objects.exclude(requested_to=organization_user)

Django makes LEFT OUTER JOINs when you filter on a ManyToManyField (or a reverse ForeignKey), so here we exclude all Requests where organization_user is a member of the requested_to.

Advertisement