Django: how to refresh or reload models from database

拥有回忆 提交于 2019-12-12 03:58:01

问题


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))

回答1:


Add "transaction-isolation = READ-COMMITTED" to my.cnf. More details here: How do I force Django to ignore any caches and reload data?



来源:https://stackoverflow.com/questions/15821581/django-how-to-refresh-or-reload-models-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!