Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a more efficient method, using a list comprehension or django's 'values_list' function?

When attempting to return a list of values from django objects, will performance be better using a list comprehension:

[x.value for x in Model.objects.all()]

or calling list() on django's values_list function:

list(Model.objects.values_list('value', flat=True))

and why?

like image 311
Kathy Rindhoops Avatar asked Dec 18 '22 17:12

Kathy Rindhoops


1 Answers

The most efficient way is to do the second approach (using values_list()). The reason for this is that this modifies the SQL query that is sent to the database to only select the values provided.

The first approach FIRST selects all values from the database, and after that filters them again. So you have already "spend" the resources to fetch all values with that approach.

You can compare the queries generated by wrapping your QuerySet with str(queryset.query) and it will return the actual SQL query that gets executed.

See example below

class Model(models.Model):
    foo = models.CharField()
    bar = models.CharField()

str(Model.objects.all().query)  
# SELECT "model"."id", "model"."foo", "model"."bar" FROM "model"

str(Model.objects.values_list("foo").query)
# SELECT "model"."foo" FROM "model"
like image 103
Marcus Lind Avatar answered May 03 '23 14:05

Marcus Lind