Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django caching queries (I don't want it to)

So I'm currently working in Python/Django and I have a problem where Django caches querysets "within a session".

If I run python manage.py shell and do so:

>>> from myproject.services.models import *
>>> test = TestModel.objects.filter(pk = 5)
>>> print test[0].name
>>> John

Now, if I then update it directly in SQL to Bob and run it again, it'll still say John. If I however CTRL+D out (exit) and run the same thing, it will have updated and will now print Bob.

My problem is that I'm running a SOAP service in a screen and it'll always return the same result, even if the data gets changed.

I need a way to force the query to actually pull the data from the database again, not just pull the cached data. I could just use raw queries but that doesn't feel like a solution to me, any ideas?

like image 281
GunniH Avatar asked Jan 09 '23 05:01

GunniH


1 Answers

The queryset is not cached 'within a session'.

The Django documentation: Caching and QuerySets mentions:

Each QuerySet contains a cache to minimize database access. Understanding how it works will allow you to write the most efficient code.

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.

Keep this caching behavior in mind, because it may bite you if you don’t use your QuerySets correctly.

(emphasis mine)

For more information on when querysets are evaluated, refer to this link.

If it is critical for your application that he querysets gets updated, you have to evaluate it each time, be it within a single view function, or with ajax.

It is like running a SQL query again and again. Like old times when no querysets have been available and you kept the data in some structure that you had to refresh.

like image 114
Wtower Avatar answered Jan 15 '23 06:01

Wtower