开发者

A row in MySQL doesn't change, even after I update it in mysql

if __name__ == "__main__":
    while True:
        results = None
        results = Decay.objects.filter(next_decay_at__lte=datetime.datetime.now())
        for r in results:
            print r.next_decay_at

        time.sleep(10)

For some reason, even if I update "next_decay_at" in the table, this Decay.objects.filter query seems to be cached and when I print "next_decay_at", it didn't seem to change! It prints the same everytime.

When I restart the script, it seems to have changed and the p开发者_JAVA技巧rint statement changed. But then when I let it run again, it prints the same over and over. Could it be that the while loop is caching the result set?


Read about Django's transaction handling.


QuerySet caches the results. To quote the docs:

In a newly created QuerySet, the cache is empty. The first time a QuerySet is evaluated -- and, hence, a database query happens -- Django saves the query results in the QuerySet's cache and returns the results that have been explicitly requested (e.g., the next element, if the QuerySet is being iterated over). Subsequent evaluations of the QuerySet reuse the cached results.

Change your code to the following:

date_from = datetime.datetime.now()
for r in Decay.objects.filter(next_decay_at__lte=date_from):
    print r.next_decay_at

Or use iterator method:

results = Decay.objects.filter(next_decay_at__lte=datetime.datetime.now())
for r in results.iterator():
    print r.next_decay_at


The behavior you're seeing has nothing to do with QuerySet. It has to do with transaction management. When your request or script starts, Django opens a transaction, and until that transaction commits or rolls back, it isn't getting anything that intermittently happens in other transactions.

If you commit your transaction and run that code block again, you should get updated results.

from django.db import transaction
transaction.commit()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜