Return 没有自我的实例列表的方法
Method to Return List of Instances Without Self
我经常 运行 进行操作以确定 class 的 "live" 个实例的列表。为了确定一个实例是否存在,它正在根据我当前 class 的 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() 并获得所有游戏的列表。
使用 @staticmethod
装饰器将 class 方法声明为静态方法。然后您不需要将 self
传递给函数。与其在函数内直接使用 Game
,不如将游戏对象作为参数传递给函数。我已经使用条件列表理解来生成比使用 append
.
更有效的结果
@staticmethod
def live_game_list(game_objects):
return [game for game in game_objects.all() if game.is_live]
为此,您需要跟踪单个实例本身之外的所有 Game
实例。您可以在任何地方执行此操作,但一种选择是使用 class 级列表:
class Game(models.Model):
all_game_instances = []
def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.all_game_instances.append(self) # accesses class attribute list
@classmethod
def live_game_list(cls):
return [game for game in cls.all_game_instances if game.is_live()]
def is_live(self):
...
然后您可以使用Game.live_game_list()
访问游戏列表。
我经常 运行 进行操作以确定 class 的 "live" 个实例的列表。为了确定一个实例是否存在,它正在根据我当前 class 的 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() 并获得所有游戏的列表。
使用 @staticmethod
装饰器将 class 方法声明为静态方法。然后您不需要将 self
传递给函数。与其在函数内直接使用 Game
,不如将游戏对象作为参数传递给函数。我已经使用条件列表理解来生成比使用 append
.
@staticmethod
def live_game_list(game_objects):
return [game for game in game_objects.all() if game.is_live]
为此,您需要跟踪单个实例本身之外的所有 Game
实例。您可以在任何地方执行此操作,但一种选择是使用 class 级列表:
class Game(models.Model):
all_game_instances = []
def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.all_game_instances.append(self) # accesses class attribute list
@classmethod
def live_game_list(cls):
return [game for game in cls.all_game_instances if game.is_live()]
def is_live(self):
...
然后您可以使用Game.live_game_list()
访问游戏列表。