On May 24, 1:12 pm, omat <o...@gezgin.com> wrote:
> Hi All,
>
> I have a Quiz model, which is related to the User model by a
> ForeignKey. I want to get a queryset of users that have a certain
> score.
>
> I want to avoid:
>
> User.objects.filter(id__in=[u.id for u in
> Quiz.objects.filter(score__gt=90)])
>
> As there are about 1 million users, this is deadly slow.
>
> What is the optimal way of doing this?

User.objects.filter(id__in=Quiz.objects.filter(score__gt=90))

This will do a subquery to get the quiz ids completely within the
database, rather than evaluating them all, instantiating Python
objects, and passing the list back into the db.

--
DR,

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to