quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

Inefficient database queries #56

Closed tomleo closed 9 years ago

tomleo commented 9 years ago

In the example

cars = Cars.objects.all()
for car in cars:
    do_something(car.make)

The call cars = Cars.objects.all() isn't retrieving ALL data from your database. It's only when the QuerySet is evaluated that a call is made to the database. In this case that is being done via the for in statement. Also upon evaluation, the data from the QuerySet is cached, so subsequent for loops do not hit the database.

If your goal is to just get the makes of all the cars, then values_list would be a better solution.

cars = Cars.objects.all().values_list('make', flat=True)
for make in cars:
    do_something(make)
programmdesign commented 9 years ago

@tomleo thanks for the feedback. I'll look into it asap.