Query API: get all users without a group

178 views
Skip to first unread message

Thomas Guettler

unread,
Dec 2, 2008, 10:45:24 AM12/2/08
to django...@googlegroups.com
Hi,

I want to get all objects where the corresponding many-to-many field is
empty.

Example: get all users without a group

My solution:
User.objects.exclude(groups__in=Group.objects.all())

I think this is not optimal, since Group.objects.all() gets evaluated.

Resulting SQL:

SELECT "auth_user"."id", "auth_user"."username",
"auth_user"."first_name", "auth_user"."last_name",
"auth_user"."email", "auth_user"."password", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."is_superuser",
"auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE
NOT ("auth_user"."id" IN (SELECT U1."user_id" FROM "auth_user" U0
INNER JOIN "auth_user_groups" U1 ON (U0."id" = U1."user_id")
WHERE U1."group_id" IN (9, 10, 11, 8))) LIMIT 21

Any better way to do this?

Should the extra() method be used for this?

Thomas


--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

Filip Wasilewski

unread,
Dec 2, 2008, 12:18:33 PM12/2/08
to Django users
On 2 Gru, 16:45, Thomas Guettler <h...@tbz-pariv.de> wrote:
> Hi,
>
> I want to get all objects where the corresponding many-to-many field is
> empty.
>
> Example:  get all users without a group
[...]

The preferred solution is using the `isnull` filter:

User.objects.filter(groups__isnull=True)

It evaluates to a left join of the `auth_user` table with
`auth_user_groups` and a simple `where` statement.

fw

alex....@gmail.com

unread,
Dec 2, 2008, 1:41:56 PM12/2/08
to Django users
You could do User.objects.exclude(groups__in=Group.objects.all
().query) which will actually generate a subquery.

Alex
> Thomas Guettler,http://www.thomas-guettler.de/

Thomas Guettler

unread,
Dec 3, 2008, 3:27:40 AM12/3/08
to django...@googlegroups.com
Filip Wasilewski schrieb:
Thank you! Django ORM is great.
Reply all
Reply to author
Forward
0 new messages