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?
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:
repr()
len()
list()
bool()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With