Django:我如何通过昂贵的计算属性对类进行排序并使结果持久?

时间:2013-09-09 17:12:23

标签: django django-models

通过昂贵的属性值对模型元素进行排序的最佳方法是什么,并确保属性值在许多请求/响应迭代中保持不变?我可能会尝试类似的东西:

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标记包装时,我不想实际创建/保存这些数据表。

0 个答案:

没有答案