2

I am no python expert and I am curious about how django optimize the following query

Model.objects.filter(field = 'abc')[0]

Somehow django will intelligently add 'limit 1' to SQL query like 'select * from model where field = 'abc' limit 1'

James Lin
  • 25,028
  • 36
  • 133
  • 233

1 Answers1

1

This is because Model.objects.filter(...) doesn't actually return a list, it returns a queryset object. When you do qset[0], it calls the __getitem__ method on querysets, which adds the limit 1 and executes it. Here's the source of that method; there's logic for various cases when the result has already been cached or not and so on.

Danica
  • 28,423
  • 6
  • 90
  • 122
  • OK, plus reading this http://stackoverflow.com/questions/2936863/python-implementing-slicing-in-getitem makes more sense now... – James Lin Nov 06 '12 at 03:30