python - QuerySet caching: executing get after filter was fired -
how many database queries executed following code:
q = somemodel.objects.filter(pk__in=ids) print q # actual query executed , result # set evaluated m = q.get(pk=ids[0]) print m # reuse evaluated result set # or hit database second time?
since querysets evaluated lazily if do:
q = somemodel.objects.filter(pk__in=ids)
...immediately folllowed (i.e., without using print
):
m = q.get(pk=ids[0])
you'll end 1 sql query. it'll and
first query second. it's safe continue adding querysets way. in django 1.3 logging revamped , can nice logging in interactive console:
>>> import logging >>> l = logging.getlogger('django.db.backends') >>> l.setlevel(logging.debug) >>> l.addhandler(logging.streamhandler())
which give sort of debugging info actual query executed:
(0.013) select "someapp_somemodel"."id", "someapp_somemodel"."question", "someapp_somemodel"."pub_date" "someapp_somemodel" ("someapp_somemodel"."id" in (0, 1) , "someapp_somemodel"."id" = 0 ); args=(0, 1, 0)
don't use get
on filtered queryset. if model want in queryset, use python expression (like list comprehension or filter
or such) model instance out of queryset, , avoid hitting database @ second time (or many more times if iterate on list of id's).
Comments
Post a Comment