Select all users that have undone jobs (select, groupby, count)

13 views
Skip to first unread message

muzhig

unread,
Aug 29, 2011, 8:17:10 AM8/29/11
to django...@googlegroups.com
Hello!
I have model Job, that is linked to User.
Job has flag `done` that indicates progress of this job.

How to select list of all users, that have undone jobs, annotated by count of this undone jobs?

I need this dict: { user1: 4, user2:12 .... }

Babatunde Akinyanmi

unread,
Aug 29, 2011, 10:02:21 AM8/29/11
to django...@googlegroups.com
I think the best way is to create a custom manager for the job (check
the documentation for details-managers). In the manager, do a query
that gets all the users with undone jobs by using the filter option
(also see the documentation - making queries). From the resulting
querydict you could count the occurrence of each unique user in the
querydict to form your dictionary. This could be potentially
inefficient so make sure you save the first query in a variable and
work with that variable.

Meanwhile someone else might know a less verbose way to do it.

> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/948LTdoWGq4J.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

--
Sent from my mobile device

christian.posta

unread,
Aug 29, 2011, 3:44:39 PM8/29/11
to Django users
Try something like this:

users = User.objects.filter(job__done=False).annotate(Count('job'))

Then each object returned will be a 'User' object with a property
named 'job__count'

ex:

users[0].job__count
Reply all
Reply to author
Forward
0 new messages