Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 聚合和注释vs信号的效率_Django_Aggregate_Django Aggregation - Fatal编程技术网

Django 聚合和注释vs信号的效率

Django 聚合和注释vs信号的效率,django,aggregate,django-aggregation,Django,Aggregate,Django Aggregation,我想计算一个用户对我的网站所做贡献的数量,这样我就可以在网站上对他们进行排名。我成功地编写了一些漂亮的代码,它确实做到了这一点,但是是基于每个用户的 由于用户对不同字段获得的点数不同,因此它会检查模型上的某些字段以及用户是否在其中输入了值。然后将这些值与其权重相乘,得到总分 没有什么比一点代码更能说明问题: class UserContribCounter(object): """Can count the number of points a user got for his cont

我想计算一个用户对我的网站所做贡献的数量,这样我就可以在网站上对他们进行排名。我成功地编写了一些漂亮的代码,它确实做到了这一点,但是是基于每个用户的

由于用户对不同字段获得的点数不同,因此它会检查模型上的某些字段以及用户是否在其中输入了值。然后将这些值与其权重相乘,得到总分

没有什么比一点代码更能说明问题:

class UserContribCounter(object):
    """Can count the number of points a user got for his contributions"""
    weight_dict = {'poster':2, 'title':1}

    def __init__(self, user):
        if isinstance(user, User):
            self.user = user
        else:
            raise Exception('Not a valid user instance.')

    def set_contrib_points(self):
        """Some dark magic counts the number of times a certain field was filled out"""
        self.unweighted = Movie.objects.filter(user = self.user).aggregate(poster=Count('poster'),title=Count('title'))

    def get_contrib_points(self):
        """Multiplies the number of times a field was filled out with their weights to calculate the total number of points"""
        try:
            self.unweighted
        except AttributeError:
            self.set_contrib_points()

        return sum([self.weight_dict[key] * value for key, value in self.unweighted.items()])
我还想展示前10名,所以我需要获得前10名用户。这意味着我将不得不编写一个复杂的聚合,而目前我一直未能做到这一点,或者我可以通过以下方式使用信号:

保存模型时,捕捉post_保存信号。然后使用我现有的类为用户重新计算点数,并将其存储在用户配置文件中。通过这种方式,我可以根据用户配置文件中的值对用户进行排序,这很简单

问题是,在每次保存模型时重新计算,或者使用一个相当复杂的聚合函数,哪种方法更有效。我知道这将取决于很多事情,但我确信,从概念的角度来看,应该有理由选择一个而不是另一个。请注意,我将在聚合中检查的一些字段也将是关系字段,因此我不确定这将如何影响性能

提前感谢,


tBuLi

我想说,这取决于你的模型改变的频率,以及你的前十名的准确度和最新程度。不管它值多少钱,你都可以将前10名缓存一小时甚至一天。另一方面,如果您必须执行django的聚合中未包含的一些复杂的排序或处理,那么您将受益于非规范化

最后,这一切都归结为实际发现了现实世界使用中的瓶颈。认真地先做尽可能小的事情