按昂贵的属性值对模型元素进行排序并确保属性值在许多请求/响应迭代中持续存在的最佳方法是什么?我可能会尝试类似:
class Player(models.Model):
name = models.CharField(max_length=100)
@classmethod
def sorted_by_player_scores(cls, league):
'would be very nice to be able to use a simple query here'
from operator import itemgetter
try:
return sorted(cls.player_score_list, key=itemgetter(1), reverse=True)
except Attribute Error:
players = cls.objects.all()
for player in players:
player_score_list = []
try:
player_score_list.append((player, player.player_score))
except AttributeError:
league_player = LeaguePlayer(league, player)
player_score_list.append((player, league_player.player_score))
cls.player_score_list = player_score_list
return sorted(player_score_list, key=itemgetter(1), reverse=True)
class League(models.Model):
name = models.CharField(max_length=100)
league_size = models.IntegerField()
scoring_rules = ...
class LeaguePlayer():
def __init__(self, league, player):
self.league = league
self.player = player
@property # is cached_property usable/useful here?
def player_score(self):
self.player.player_score = very_expensive_calculation()
return self.player.player_score
def many_other_properties_and_methods_against_LeaguePlayers
我觉得我的问题将是一个常见的 django 问题,但我找不到一个简单的解决方案,甚至找不到一些一般的最佳实践讨论。我知道我可以制作class LeaguePlayer()
一个 django 模型,而不仅仅是一个 python 类。@property
但是当我要保存的值很容易被标签包装时,我不想实际创建/保存这些数据表。