Let's say I have a model like this:
class A(models.Model):
title = models.CharField(max_length=10)
(more fields)
I want to fetch value of just title field of an instance. I can either use filter
:
A.objects.filter(id=1).values_list('title', flat=True)
which generates a SQL statement like this:
SELECT "app_table_a"."title" FROM "app_table_a" WHERE ("app_table_a"."a_id" = 1) LIMIT whatever
or use get
:
A.objects.get(id=1).title
which generates this:
SELECT "app_table_a"."id", "app_table_a"."title", ... ,"app_table_a"."all the fields in the model" FROM "app_table_a" WHERE ("app_table_a"."a_id" = 1)
The difference is in SELECT
part of queries, which gives the impression that the first approach is a better option. But when I look at execution time of those statements, I don't see a meaningful difference and both statements fluctuate around, for example, 25ms.
So, my question is whether there is any difference, performance-wise (specially with huge databases and models with many fields), or I am just twisting everything with long statements?
Yes, i agree with you.There is no much significant difference in between them(in perfomance when only one record) because, behind the scenes the django
get()
method runs thefilter()
method, but checks that the filter results set is exactly one record.