django - Python variable scope and lazy querysets -
i'm using django , out-of-the-box orm. if there module level variables, evaluated when app starts? or evaluated on every request if it's modified in view? example:
from news.models import news # module level variables draft_news = news.objects.filter(status='draft') live_news = news.objects.filter(status='prod') def view(request): # outputs 10 10, respectively. print 'there %d news objects , %d live objects. adding draft article' % (draft_news.count(), live_news.count()) n = news( content='this test content', status='draft', slug='this-is-a-test3', pubdatetime=datetime.now(), ) n.save() print '...done. there %d draft news objects.' % draft_news.count() # 11 objects print 'changing status live...' n.status='prod' n.save() print 'there %d live objects.' % live_news.count() # 11 objects
since querysets lazy, matter if in module level or view level? tested above code in management command.
let's assume refactoring not option.
additional information: have several app servers (uwsgi) sharing same database. seems module level variables changed when restart uwsgi processes on of them. in other words, new news object returns 404 when using get_object_or_404 in view.
no, doesn't matter if in module level or view level.
the declaration doesn't fire db request. when ask concrete result (such count or start iterating) actual db hit happen.
it advisable keep them on view level keep global namespace clean.
update:
problem .count()
giving outdated results more connected django db query caching rather laziness. consider this question page workarounds.
Comments
Post a Comment