如何禁用 Django 查询缓存? [英] How to disable Django query cache?

查看:28
本文介绍了如何禁用 Django 查询缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Django 应用程序中,我在我的数据库上反复运行相同的查询(例如每 10 秒).然后,我在收到的查询集上创建一个 MD5 总和,并将其与我在上次运行中创建的 MD5 总和进行比较.如果两者相等,则数据没有改变,网页不需要更新.

当我这样做时,数据库中的数据可能会发生变化.

然而,查询返回相同的查询集,显然是由于 查询缓存.

如何禁用查询缓存并在数据库上显式执行查询?

解决方案

我遇到了一些我认为是某种缓存的行为,但结果证明是数据库事务在愚弄我.

我遇到了一个问题,在另一个进程中,项目被添加到数据库中,我想监控另一个进程的进度,所以我打开了一个 django shell 并发出以下命令:

<预><代码>>>>MyData.objects.count()74674>>>MyData.objects.count()74674

该值没有改变,即使它实际上在数据库中.我意识到至少以我拥有 MySQL 的方式 &django 设置,我在一个事务中,并且在我打开事务时只会看到数据库的快照".

由于在 django 中使用视图,我定义了自动提交行为,这对于每个视图只能看到一个快照是没问题的,因为下次调用视图时它将在不同的事务中.但是对于一段没有自动提交的代码,除了在这个事务中所做的那些之外,它不会在数据库中看到任何变化.

只是想我会把这个答案扔给任何可能遇到这种情况的人.

要解决,提交您的事务,可以像这样手动完成:

<代码>>>从 django.db 导入事务>>transaction.enter_transaction_management()>>transaction.commit() # 每当您想查看新数据时

In my Django application, I repeatedly run the same query on my database (e.g. every 10 seconds). I then create an MD5 sum over the queryset I receive and compare that to the MD5 sum I created in the previous run. If both are equal, the data has not changed and the web page does not need updating.

While I do this, the data in the DB might change.

However, the query returns the same queryset, apparently due to query caching.

How can I disable the query cache and explicitely execute the query on the DB ?

解决方案

I came across behavior that I thought was some kind of caching, but it turned out to be database transactions fooling me.

I had the problem where in another process, items were get added to the database, and I wanted to monitor progress of the other process, so I opened up a django shell and issued the following:

>>> MyData.objects.count()
74674

>>> MyData.objects.count()
74674

The value wasn't changing, even though it actually was in the database. I realized that at least with the way I had MySQL & django setup that I was in a transaction and would only see a "snapshot" of the database at the time I opened the transaction.

Since with views in django, I had autocommit behavior defined, this was fine for each view to only see a snapshot, as the next time a view was called it would be in a different transaction. But for a piece of code that was not automatically committing, it would not see any changes in the db except those that were made in this transaction.

Just thought I would toss this answer in for anyone who may come upon this situation.

To solve, commit your transaction, which can be manually done like so:

>> from django.db import transaction
>> transaction.enter_transaction_management()
>> transaction.commit() # Whenever you want to see new data

这篇关于如何禁用 Django 查询缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆