Home > Blockchain >  does performing a `get` on a queryset evaluates the whole queryset or just one element of queryset?
does performing a `get` on a queryset evaluates the whole queryset or just one element of queryset?

Time:06-07

pseudocode:


class TestModel(models.Model):
    a = models.CharField()
    b = models.CharField()

qs = Model.objects.filter(a="something") # returns qs containing 5 objects

obj = qs.get(b='something_else') # evaluates the queryset and hits the db

obj2 = qs.get(b='something_else_2') # evaluates again? hits db again?

Now while assigning to obj2, will it hit db again? or even will it hit db while assigning to obj?

CodePudding user response:

QuerySets are lazy, that means that your qs will not be evaluated, unless you somehow "consume" it (for example by iterating over it, call len(…), str(…) on it, etc.).

You use qs as a basic queryset to make two queries with the two .get(…) calls. These will each result in a single query that aims to fetch a single record. Django will thus make two queries, one with:

SELECT model.a, model.b FROM model WHERE a=something and b=something_else

and:

SELECT model.a, model.b FROM model WHERE a=something and b=something_else_2

First constructing a common queryset qs will thus have no performance impact, but can for example be more convenient in terms of software design.

  • Related