Caching at QuerySet level in Django

I'm trying to get a queryset from the cache, but am unsure if this even has a point.

I have the following method inside a custom queryset:

    def queryset_from_cache(self, key: str=None, timeout: int=60):
        # Generate a key based on the query.
        if key is None:
            key = self.__generate_key # ()

        # If the cache has the key, return the cached object.
        cached_object = cache.get(key, None)

        # If the cache doesn't have the key, set the cache, and then return the cached object.
        if cached_object is None:
            cache.set(key, self, timeout=timeout)

        return cached_object

The usage is basically to append it to a django QuerySet method, for example:

queryset = MyModel.objects.filter(name__in=["Jane","John"]).queryset_from_cache()
Finally, my question:

Would usage like this work? Or would it try to hit the database no matter what?

This is a really cool idea, but I'm not sure if you can Cache full-on Objects.. I think it's only attributes

Now this having a point. Grom what I'm seeing from the limited code I've seen idk if it does have a point, unless filtering for Jane and John (and only them) is very common. Very narrow. Maybe just try caching ALL the users or just individual Users, and only the attributes you need

Back to Top