在连续循环脚本中,数据库数据中的更改未反映在Django查询集中 [英] Changes in DB data not reflecting in the Django queryset in a continuously looping script
问题描述
我正在使用Django的ORM从Db获取新添加的条目,并将它们传递到消息队列。我在无限的while循环中执行此操作,即使在运行此脚本时添加/删除/编辑条目,每次循环迭代中的问题我都得到相同的查询集。
I am using Django's ORM to get newly added entries from a Db and pass them to a Messaging queue. I am doing this in an infinite while loop , The PROBLEM in every loop iteration I am getting the same queryset even when I have added/deleted/edited entries when this script is running,
代码如下:
while True :
sleep(10 seconds)
# Below is the problem line, I get the same query-set every time in new_objects
# even when I have added/deleted/edited entries while this daemon is running.
new_objects = Model.objects.filter(some condition)
# Process new_objects and send them to MQ
.
. and so on
我应该怎么做才能在每次迭代中反映最新数据?
What should I do to reflect the latest data in each iteration ?
推荐答案
这与缓存无关。
默认情况下,连续运行的脚本在单个事务中运行,因此永远不会在该事务之外看到更改。您需要在每次迭代中手动启动新事务-请参见交易文档有关如何操作的信息。
A continuously-running script by default runs within a single transaction, and so will never see changes outside that transaction. You'll need to start a new transaction manually on every iteration - see the transaction documentation on how to do that.
这篇关于在连续循环脚本中,数据库数据中的更改未反映在Django查询集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!