queryset exclude fails across a many-to-many list
|Reported by:||Owned by:||nobody|
|Severity:||Keywords:||exclude m2m many-to-many, qs-rf-fixed|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Description (last modified by )
If you try to exclude items from a queryset across a m2m link, it fails to give the expected result.
For instance, assuming I have users, some of whom are in group Editors, some in group Sales, and most are not in a group at all.
from django.contrib.auth.models import User user_qs = User.objects.all() # all users non_editor_users = user_qs.exclude(groups__name='Editors') # should be all users excluding those in group Editors
The set wrongly returned is actually the set of users who are in Sales but not in Editors - it fails to include those users who have no group at all.
The reason is the sql clause generated, which is doing
FROM "auth_user" LEFT OUTER JOIN "auth_user_groups" AS "m2m_auth_user__groups" ON "auth_user"."id" = "m2m_auth_user__groups"."user_id" INNER JOIN "auth_group" AS "auth_user__groups" ON "m2m_auth_user__groups"."group_id" = "auth_user__groups"."id" WHERE ((NOT ("auth_user__groups"."name" = %s))) ORDER BY "auth_user"."username" ASC', ['Editors']
A workaround for this was posted some time back in http://groups.google.com/group/django-users/browse_thread/thread/81eb405071037248/2beb073a93fd68b7
I can't find a ticket for it - please excuse me if it's a duplicate. I guess #2091 might be related under the hood.
Change History (4)
comment:1 Changed 9 years ago by
|Owner:||changed from Adrian Holovaty to Malcolm Tredinnick|
|Patch needs improvement:||unset|