我正在使用Django及其開箱即用的ORM。如果有一些模塊級變量,它們是否僅在應用程序啓動時才被評估?或者,如果在視圖中修改了它們,它們是否也會對每個請求進行評估?例如:Python變量作用域和延遲查詢集
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 an 10, respectively.
print 'There are %d news objects and %d live objects. Adding a draft article' % (draft_news.count(), live_news.count())
n = News(
content='This is test content',
status='draft',
slug='this-is-a-test3',
pubdatetime=datetime.now(),
)
n.save()
print '...done. There are %d draft news objects.' % draft_news.count() # 11 objects
print 'Changing status to live...'
n.status='prod'
n.save()
print 'There are now %d live objects.' % live_news.count() # 11 objects
由於查詢集是懶惰的,它們是否在模塊級別或視圖級別有關係嗎?我最初在管理命令中測試了上述代碼。
我們假設重構不是一個選項。
其他信息:我有幾個應用程序服務器(uWSGI)共享相同的數據庫。看來只有當我重啓所有這些進程的uWSGI進程時,模塊級變量纔會發生變化。換句話說,當在視圖中使用get_object_or_404時,新的News對象返回404。
Django或類似SQLAlchemy?如果我們歸結爲特定的ORM可能會有所幫助。 – CppLearner
@CppLearner django。我更新了我的問題。 – Chris