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‘
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is because
Model.objects.filter(...)doesn’t actually return a list, it returns a queryset object. When you doqset[0], it calls the__getitem__method on querysets, which adds thelimit 1and 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.