2013-04-04 113 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

回答