Django ORM查询无法选择新对象 [英] Django ORM queries fail to select new objects
问题描述
设置:
- Python脚本 A 将数据插入到DB中第15分钟
- Python脚本 B 每隔几分钟查询最后5个条目
- Python script A inserts data to a DB every round 15 minutes
- Python script B queries for the last 5 entries every few minutes
都使用django的ORM,相同的MySQL数据库和同一个DB用户帐户(相同的 settings.py
文件)
Both use django's ORM, same MySQL DB and the same DB user account (same settings.py
file)
问题:
B 只能在运行前插入插入的条目。如果 B 正在运行一个冻结的数据库,那么在 B 之前冻结,首先连接到数据库。
The Problem:
B is able to fetch only entries inserted before it was run. As if B is running with a frozen DB, frozen at the moment B first connected to the DB.
怎么来?
我可以在django中控制这个行为吗?
How come?
Can I control this behavior in django?
推荐答案
如果你重复使用同一个经理对象,你必须牢记它的缓存一>。要处理,您必须手动更新。
If you're reusing same Manager object, you have to keep in mind it's caching. To deal with that you have to manually update.
这将在每次迭代中返回相同的结果:
This will return same results in every iteration:
while True:
same_every_time = AClass.objects.all().order_by('-id')[:5]
sleep(300)
为了使其正常工作,您必须添加更新:
In order to make it work properly you have to add the update:
while True:
AClass.objects.update()
updated_results = AClass.objects.all().order_by('-id')[:5]
sleep(300)
这篇关于Django ORM查询无法选择新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!