2013-04-04 90 views
0

數據庫中的一些表格是由Django之外的幾個python腳本更新的。因此,Django的視圖不知道數據庫中的最新數據,並顯示舊數據。我在網上嘗試過很多建議,但除了在使用模型之前調用connection.close()之外沒有任何工作。Django:如何從數據庫刷新或重新加載模型

下面是我嘗試過的方法,沒有任何工作。

from django.views.decorators.cache import never_cache 

@never_cache # <===== 
def GetData(request): 
    data = Table.objects.get(id=1) # Still giving outdated data 

    template = loader.get_template('data/data.html') 
    context = Context({ 
     'lp': lp, 
    }) 
    return HttpResponse(template.render(context)) 

data = Data.objects.get(id=1) 
data = data.objects.get(id=data.id) # data is still old 

from django.core.cache import cache 
cache.clear() 

時運作的方法。

from django.db import connection 
def GetData(request): 
    # Add this before accessing the model. 
    # This also connection.close() prevents the 
    # MySQL 2006, 'MySQL server has gone away' error. 
    connection.close() 

    data = Table.objects.get(id=1) # Giving outdated data 

    template = loader.get_template('data/data.html') 
    context = Context({ 
     'lp': lp, 
    }) 
    return HttpResponse(template.render(context)) 
+0

這是一個類似的問題。 http://stackoverflow.com/questions/3346124/how-do-i-force-django-to-ignore-any-caches-and-reload-data – Terry 2013-04-04 23:41:51

回答