[Django]-Django transaction.commit() needed after Model.objects.filter() when object was saved from another process

4👍

Since you’re using transaction middleware, each request gets a different transaction.

The recommended way to handle transactions in Web requests is to tie them to the request and response phases via Django’s TransactionMiddleware.

It works like this: When a request starts, Django starts a transaction. If the response is produced without problems, Django commits any pending transactions. If the view function produces an exception, Django rolls back any pending transactions.

This means that if the second process’s request came in before the write was triggered, its transaction will predate the write. The database will then do the right thing and report the value that was current at the time the second process’s transaction was created. Manually committing the second process’s transaction before reading is harmless (as long as it has made no edits) and tells the database to create a new transaction. Which will postdate write, and therefore give you the modified results.

1👍

I ran into this issue too. Django caches the query results (which is a good thing for a single process). If the second process has a cache of the same query, it won’t see the update until the cache is flushed.

For some reason, transaction.commit() flushes the cache, so it helps with this problem. Call that method right before you run your query and you should see results directly from the database.

Leave a comment