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)
In the example
The call
cars = Cars.objects.all()
isn't retrieving ALL data from your database. It's only when theQuerySet
is evaluated that a call is made to the database. In this case that is being done via thefor in
statement. Also upon evaluation, the data from theQuerySet
is cached, so subsequentfor
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.