Django:如何从数据库刷新或重新加载模型 [英] Django: how to refresh or reload models from database
本文介绍了Django:如何从数据库刷新或重新加载模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我尝试的方法,没有任何工作。
从django.views.decorators.cache导入never_cache
@never_cache#< ; =====
def GetData(request):
data = Table.objects.get(id = 1)#仍然提供过时的数据
template = loader.get_template ('data / data.html')
context = Context({
'lp':lp,
})
返回HttpResponse(template.render(context))
data = .objects.get(id = 1)
data = data.objects.get(id = data.id)#data is old old
从django.core.cache导入缓存
cache.clear()
有效的方法。:
from django.db import connection
def GetDat a(请求):
#在访问模型之前添加它。
#这也是connection.close()阻止
#MySQL 2006,MySQL服务器已经消失的错误。
connection.close()
data = Table.objects.get(id = 1)#给出过时的数据
template = loader.get_template('data / data.html')
context = Context({
'lp':lp,
})
返回HttpResponse(template.render(context))
解决方案
将transaction-isolation = READ-COMMITTED添加到my.cnf。更多详细信息:如何强制Django忽略任何缓存并重新加载数据?
Some of my tables in database are periodicity updated by several python scripts outside of Django. As a result, the Django's views are not aware of the latest data in database and is showing the old data. I have tried many suggestions online but nothing work except called connection.close() before using the model.
Here are the approaches I have tried, nothing worked.
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()
The approach that works.:
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))
解决方案
Add "transaction-isolation = READ-COMMITTED" to my.cnf. More details here: How do I force Django to ignore any caches and reload data?
这篇关于Django:如何从数据库刷新或重新加载模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文