我有一个查询数据库属性的类。正如您在下面的代码中看到的,我需要设置candidates
属性,然后根据prime
属性设置candidates
属性。但是,我想避免两次查询数据库。最好的方法是什么?
class Event(object):
def __init__(self):
pass
@property
def candidates(self):
# get candidates from db
return query_result
@property
def prime(self):
# get prime based on complex logic with candidates. Simplified eg:
return self.candidates[0] # hits db again :(
如果我在self.prime
定义中设置candidates
,但在prime
之前调用candidates
,我将收到错误消息。最好的方法是什么?
答案 0 :(得分:1)
将结果缓存在私有变量中。
class Event(object):
def __init__(self):
self._candidates = None
@property
def candidates(self):
# get candidates from db
self._candidates = query_result
return query_result
@property
def prime(self):
# get prime based on complex logic with candidates. Simplified eg:
return self._candidates[0]
这假设您希望每次访问candidates
属性时都访问数据库/刷新数据。如果候选属性不是那么动态,那么您可以前端查询。像这样:
@property
def candidates(self):
if self._candidates is None:
# get candidates from db
self._candidates = query_result
return self._candidates