Wednesday, November 2, 2011

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

On Wed, Nov 2, 2011 at 8:25 AM, Thomas Guettler <hv@tbz-pariv.de> wrote:
# This is my current solution
if get_special_objects().filter(pk=obj.pk).count():
   # yes, it is special


I can't speak to the "why" of this situation; it seems to me that this could always be converted into a more efficient database query without any unexpected side-effects (and if I really wanted the side effects, I would just write "if obj in list(qs)" instead). In this case, though, I would usually write something like this:

if get_special_objects().filter(pk=obj.pk).exists():
   # yes, it is special

I believe that in some cases, the exists() query can be optimized to return faster than a count() aggregation, and I think that the intent of the code appears more clearly.

Ian

--
Regards,
Ian Clelland
<clelland@gmail.com>

--
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