Wednesday, November 2, 2011

Re: QuerySet: "if obj in queryset" can be very slow

Here is a better example:

def get_special_objects():
# Some are special. But the result can still be huge!
return MyModel.objects.filter(....)

obj=MyModel.objects.get(....)

# is this object "special?"
if obj in get_special_objects(): # This is very slow if there are many rows in the result.
# yes, it is special

# This is my current solution
if get_special_objects().filter(pk=obj.pk).count():
# yes, it is special


Up to now I sometimes used "if obj in queryset" but never realized, that
this evaluates the whole queryset. Up to now I thought this is lazy.

I have no big problem with this, since I found a solution.

Is there a reason why "if obj in queryset" is executed in python code, and not
in the DB?

Thomas

Am 02.11.2011 12:42, schrieb Thomas Guettler:
> Hi,
>
> I just discovered, that "if obj in queryset" can be very slow:
>
> queryset=MyModel.objects.all()
> obj=MyModel.objects.get(id=319526)
>
> #if obj in queryset: # This is very slow, if queryset is big: All lines from queryset get created to Python objects
> # print 'in'
>
> if queryset.filter(id=obj.id): # Fast: Check is done inside DB.
> print 'in'
>
> What is the best way to do "if obj in queryset"?
>
> Thomas
>

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

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

No comments:

Post a Comment