Suor / django-cacheops

A slick ORM cache with automatic granular event-driven invalidation.
BSD 3-Clause "New" or "Revised" License
2.12k stars 227 forks source link

Question: Suggested File Convention For Cache Modules? #445

Closed billpull closed 1 year ago

billpull commented 1 year ago

Hello, I am relatively new to working within the Django framework and have seen a lot of performance gains using this project and wanted to add some structure to my project in terms of centralizing frequently used cached operations.

I know in the main settings file you can specify timeouts for specific models or apps within the project but I have found more success with translating those to dict or array lookups using the cached_as decorator. So for DRY I have been moving those to helper modules but that seems a bit too generic and wanted to see if other people in the community had a file convention they use?

Example:

I might have a user module where I want to look up all games they have been in that are active with some other relations.

def get_active_games(user):
  @cached_as(UserModel, Game, extra=(user.id), timeout=60*15)
  def _get_active_games():
       active_games = Game.objects.filter(user=user, status='active').select_related('team')
       return {game.id: {'game': game, 'team': game.team} for game in active_games}

  return _get_active_games()

If I have several of these type of user specific cached functions or QS where would I put that in a django project?

/users
   -- models.py
   -- views.py
   -- serializers.py
   -- *cache.py* (?)
Suor commented 1 year ago

Those functions being cached might be or not be their defining trait. If that is so then making a separate file with some name containing "cache" makes sense. Otherwise they can either sit along with code calling them or grouped with other related code, with no concern of whether they are cached or not.