我的 UserProfile 对象上有几个 TextField 列,其中包含 JSON 对象。我还为每一列定义了一个 setter/getter 属性,它封装了将 JSON 序列化和反序列化为 python 数据结构的逻辑。
此数据的性质确保将在单个请求中通过视图和模板逻辑多次访问它。为了节省反序列化成本,我想在读取时记住 python 数据结构,在直接写入属性或保存模型对象的信号时失效。
我在哪里/如何存储备忘录?我对使用实例变量感到紧张,因为我不了解查询实例化任何特定 UserProfile 背后的魔力。使用安全,还是我__init__
需要hasattr()
在每次读取时检查 memo 属性的存在?
这是我当前实现的一个示例:
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)