Opened 17 years ago

Last modified 17 years ago

#5324 closed

queryset exclude fails across a many-to-many list — at Initial Version

Reported by: Robert Bunting <robert@…> Owned by: Adrian Holovaty
Component: Core (Other) Version: dev
Severity: Keywords: exclude m2m many-to-many, qs-rf-fixed
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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.

  1. from django.contrib.auth.models import User
  2. user_qs = User.objects.all() # all users
  3. non_editor_users = user_qs.exclude(groupsname='Editors') # should be all users excluding those in group Editors

The set wrongly returned from (3) 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 (0)

Note: See TracTickets for help on using tickets.
Back to Top