Issue
Does Django know the number of instances of each model?
I was wondering... Since Django does not execute the query to the database until the Queryset is evaluated :
QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated.
Then how MODEL.objects.get(pk=1)
, for example, raises DoesNotExist
exception when there is no MODEL
instance with pk=1
, even if I stored it in a variable without printing it for example?
x = MODEL.objects.get(pk=1)
Traceback (most recent call last):
......
myAPP.models.MODEL.DoesNotExist: MODEL matching query does not exist.
Solution
Using objects.get
is not "lazy" as it does not return a QuerySet
.
Your code: MODEL.objects.get(pk=1)
will be evaluated immediately and returned as a model instance rather than a QuerySet
.
Answered By - Lewis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.