在连续循环脚本中,数据库数据的更改未反映在 Django 查询集中

发布于 2024-11-26 22:43:53 字数 508 浏览 0 评论 0 原文

我正在使用 Django 的 ORM 从数据库获取新添加的条目并将它们传递到消息队列。我在无限 while 循环中执行此操作,每次循环迭代中的问题即使在该脚本运行时添加/删除/编辑条目,我也会得到相同的查询集,

代码如下所示:

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

我应该做什么来反映每次迭代中的最新数据?

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,

The code goes like this :

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2024-12-03 22:43:53

这与缓存无关。这与交易有关。

默认情况下,连续运行的脚本在单个事务中运行,因此永远不会看到该事务之外的更改。您需要在每次迭代时手动启动新事务 - 请参阅 交易文档介绍了如何执行此操作。

This isn't anything to do with caching. This is to do with transactions.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文