Search code examples
djangocachingdjango-modelsmemcacheddjango-select-related

Django: Caching RelatedObjects using select_related


I am trying to cache a Django Model object with the RelatedObjects. But when I access the related objects, a query gets fired. Here is the code:

class Main(models.Model):
    name = models.CharField('Name', max_length=100)

class Related(models.Model):
    main = models.ForeignKey(Main, related_name="related")
    name = models.CharField('Name', max_length=100)

def cache_main_with_related():
    obj = Main.objects.select_related('related').get(name="abc")
    cache.set('cache:abc', obj)  # I want related also to get cached

def access_cache():
    cached_obj = cache.get('cache:abc')
    print cached_obj.name  # No query fired
    print cached_obj.related.all()  # This fires a DB query even though abc is cached after select_related

So when I access the cached object's related objects, the database gets hit. I see it in django.db.backends logger.

Questions:

  1. Am I doing something wrong or is this expected?

  2. Does caching not include RelatedObjects by default? Should I cache them separately then?


Solution

  • This isn't anything to do with caching; the same thing would happen if you accessed obj.related.all() in the first view. That's because select_related doesn't work on reverse relations; you'd need prefetch_related for that.