Otskimanot Sqilal
Otskimanot Sqilal

Reputation: 2402

django - when is .objects.get() evaluated?

Suppose i have :

class Library(models.Model):
    name = models.CharField(max_length = 100)

class Books(models.Model):
    library = models.ForeignKey(Library)
    book = models.CharField(max_length = 100)

I want to create a new Books, we know we can fill the library on Books with just Library's id, but we can also use instance of Library. My question is, is it better if we just provide the id? If i want to use the instance, then i have to evaluate using .get(), then does it hit the database?

Additional question : From the docs, queryset are lazy, it does not hit the database till evaluated, so when does queryset evaluated?

Upvotes: 8

Views: 3628

Answers (1)

spencer nelson
spencer nelson

Reputation: 4525

Yes, .get() is immediately evaluated. Using IDs will avoid the database query, certainly.

get isn't lazy since it does not return a QuerySet - it returns a single instance of the model. QuerySets come from stuff like .filter(), so for example Library.objects.filter(id=5) is lazily evaluated while Library.objects.get(id=5) is immediately evaluated.

The actual evaluation of a QuerySet is covered in the docs - basically, any time you actually pull out a value from the QuerySet, it will get evaluated. The complete list is this:

  • Iteration
  • Slicing
  • Pickling
  • repr()
  • len()
  • list()
  • bool()

Upvotes: 14

Related Questions