我正在尝试使用相关对象缓存 Django 模型对象。但是当我访问相关对象时,会触发一个查询。这是代码:
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
所以当我访问缓存对象的相关对象时,数据库会被命中。我在 django.db.backends 记录器中看到它。
问题:
我做错了什么还是预期的?
缓存是否默认不包括相关对象?那我应该单独缓存它们吗?