【发布时间】:2016-08-11 03:28:29
【问题描述】:
我经常运行一个操作来确定一个类的“活动”实例列表。要确定一个实例是否处于活动状态,它正在针对我当前类的 is_live 方法进行测试——请参见下文。
class Game(models.Model):
def is_live(self):
now = timezone.now()
now.astimezone(timezone.utc).replace(tzinfo=None)
if self.time is not None and now < self.time:
return True
if self.time is None:
return True
else:
return False
不必在我的所有视图中运行此循环,我更愿意创建另一个运行方法来返回所有活动实例的列表。但是,这样做我不需要使用 self 并且每次尝试这样做时都会出错。任何想法如何完成这个。循环如下所示
def live_game_list():
live_game_list = []
for game in Game.objects.all():
if game.is_live == True:
live_game_list.append(game)
return live_game_list
然后我就可以调用 Game.live_game_list() 并获取所有游戏的列表。
【问题讨论】:
标签: python django methods instance