向django模型添加迷你高速缓存

向django模型添加迷你高速缓存

本文介绍了向django模型添加迷你高速缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于m2m关系,我遇到Django的性能问题。我有一个Something_instance.item_set的Something对象的列表,所以我多次调用Something_instance.item_set.all()。我想将该查询缓存到Something_instance中,以便我不必运行这么多查询。这可能吗? (这实际上是使select_related()适用于m2m)的一个漏洞。



编辑:
以下2个片段显示了我遇到的问题。在views.py中,我正在查询m2m关系。

  for t in items:
try:
t.price = t.user_item_rel_set.get(user = u).payment_amount
除了:
t.price = -1 * t.buyer_item_rel_set.get(buyer = u).payment_amount
返回项目

另外,我的模型中的一个功能:

  def listBuyers(self):
return self.buyer_item_rel_set.all()

我有这是因为我在我的模板中使用它从这些元素获取信息。



查询m2m关系最后运行两次:在views.py中一次,然后在模板中一次。我想在视图中获取查询器,将其附加到模型实例,然后将其提供给模板,因此(和views.py代码)使用缓存的查询集,而不是再次获取。

解决方案

是的,我一直都这样做。使用listBuyers方法作为示例(顺便说一下,Pythonic约定将被称为 list_buyers ...)

  def listBuyers(self):
如果不是hasattr(self,'_buyers'):
self._buyers = self.buyer_item_rel_set.all()
return self._buyers

这将在第一次针对特定实例调用listBuyers时触发数据库,但不是之后。


I'm running into performance issues with Django because of m2m relationships. I have a list of Something objects that all have Something_instance.item_set, so I call Something_instance.item_set.all() many times. I'd like to cache that query into Something_instance so that I don't have to run so many queries. Is this possible? (This is essentially a hack for getting select_related() to work for m2m).

EDIT:The following 2 snippets shows the problem I'm having. In views.py, I'm querying the m2m relationship.

    for t in items:
          try:
              t.price = t.user_item_rel_set.get(user=u).payment_amount
          except:
              t.price = -1 * t.buyer_item_rel_set.get(buyer=u).payment_amount
    return items

Also, a function in my model:

def listBuyers(self):
    return self.buyer_item_rel_set.all()

I have this because I use it in my template to get information from those elements.

Querying the m2m relationships end up running twice: once in the views.py, and then once in the template. I'd like to get the queryset in views, attach it to the model instance, and then feed that to the template, so it (and the views.py code) uses the cached queryset, instead of fetching again.

解决方案

Yes, I do this all the time. Using your listBuyers method as an example (by the way, Pythonic convention would be to call it list_buyers...)

def listBuyers(self):
    if not hasattr(self, '_buyers'):
        self._buyers = self.buyer_item_rel_set.all()
    return self._buyers

This will hit the database the first time listBuyers is called for a particular instance, but not afterwards.

这篇关于向django模型添加迷你高速缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 14:10