如何在Django模型对象上记录昂贵的计算? [英] How do I memoize expensive calculations on Django model objects?

查看:118
本文介绍了如何在Django模型对象上记录昂贵的计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的UserProfile对象上有几个TextField列,其中包含JSON对象。我还为每个列定义了一个setter / getter属性,该属性封装了将JSON序列化和反序列化为python数据结构的逻辑。

I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures.

此数据的性质确保将在单个请求中通过视图和模板逻辑访问多次。为了节省反序列化成本,我想在读取时记录python数据结构,直接写入属性或从模型对象保存信号无效。

The nature of this data ensures that it will be accessed many times by view and template logic within a single Request. To save on deserialization costs, I would like to memoize the python datastructures on read, invalidating on direct write to the property or save signal from the model object.

哪里/如何我是否存储备忘录?我很担心使用实例变量,因为我不明白任何特定UserProfile如何被查询实例化的魔力。可以安全使用 __ init __ ,或者需要通过 hasattr()来检查memo属性的存在阅读?

Where/How do I store the memo? I'm nervous about using instance variables, as I don't understand the magic behind how any particular UserProfile is instantiated by a query. Is __init__ safe to use, or do I need to check the existence of the memo attribute via hasattr() at each read?

这是我目前实现的一个例子:

Here's an example of my current implementation:

class UserProfile(Model):
    text_json = models.TextField(default=text_defaults)

    @property
    def text(self):
        if not hasattr(self, "text_memo"):
            self.text_memo = None
        self.text_memo = self.text_memo or simplejson.loads(self.text_json)
        return self.text_memo
    @text.setter
    def text(self, value=None):
        self.text_memo = None
        self.text_json = simplejson.dumps(value)


推荐答案

您可能对内置的django装饰器感兴趣 django.utils.functional.memoize

You may be interested in a built-in django decorator django.utils.functional.memoize.

Django使用它来缓存昂贵的操作,如url解析。

Django uses this to cache expensive operation like url resolving.

这篇关于如何在Django模型对象上记录昂贵的计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆