On Wed, Nov 2, 2011 at 3:25 PM, Thomas Guettler <h...@tbz-pariv.de> wrote: > 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 > >
Choice and consistency. You've picked an edge case where it does make more sense to query the database, however I could contrive any number of examples where it would be wrong to filter in the database, for example if I had a long list of objects I wanted to test are in the queryset AND I wanted the items in the queryset constructed anyway, I'd use the 'in' operator. This is the choice. For consistency, querying the database is performed by methods on a model's manager class or related queryset, where as python functions operating on a queryset do not perform database queries. Eg, len(qs) evaluates the queryset and counts the number of instances in the queryset using python, where as qs.count() performs a DB query to obtain the result. Neither is wrong, they are appropriate in different cases. Cheers Tom -- 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+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.