Django-重用带注释的计数

Django-重用带注释的计数,django,django-orm,Django,Django Orm,我有一个模型,它允许我用我生成的散列记录错误,所以相同的错误有相同的散列,这样我就可以对它们进行分组和计数。模型看起来像这样 class ErrorLog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateTimeField(null=True, blank=True, db_index=True) log

我有一个模型,它允许我用我生成的散列记录错误,所以相同的错误有相同的散列,这样我就可以对它们进行分组和计数。模型看起来像这样

class ErrorLog(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    date = models.DateTimeField(null=True, blank=True, db_index=True)
    log = models.TextField(blank=True, null=True)
    log_hash = models.CharField(max_length=255, blank=True, null=True)  
在我看来,我执行以下查询以通过哈希计算错误

def get(self, request):
    qs = self.filter_queryset(self.get_queryset())
    total_errors = qs.count()

    qs = qs.values(
        'log_hash', 'log'
    ).annotate(
        error_count=Count('log_hash')
    ).annotate(
        percentage_of_occurrence=Concat(
            Cast(
                funcs.Round(
                    (F('error_count') / total_errors) * 100, 1
                ), CharField()
            ), Value('%')
        )
    )
这就像一个魅力,因为我可以得到我想要的结果

"results": [
        {
            "error_count": 2,
            "percentage_of_occurrence": "50.0%",
            "log_hash": "8f7744ba51869f93ce990c67bd8d3544",
            "log": "Error 1"
        },
        {
            "error_count": 1,
            "percentage_of_occurrence": "25.0%",
            "log_hash": "de54a1e3be2cab4d04d8c61f538a71df",
            "log": "Error 2"
        },
        {
            "error_count": 1,
            "percentage_of_occurrence": "25.0%",
            "log_hash": "05988dc15543ef06e803a930923d11d4",
            "log": "Error 3"
        }
    ]
问题来了,在一个大的表上这是非常慢的,所以在检查生成的SQL之后,我看到了一个问题。我计算了两次,一次是为了得到
错误\u计数
,另一次是为了计算出现的
百分比

SELECT `errorlog`.`log_hash`, `errorlog`.`log`, COUNT(`errorlog`.`log_hash`) AS `error_count`, 
((COUNT(`errorlog`.`log_hash`) / ) * 100) AS `percentage_of_occurrence` 
FROM `errorlog` 
GROUP BY `errorlog`.`log_hash`, `errorlog`.`log`
ORDER BY `error_count` DESC

是否有任何方法可以重复使用第一次计数来计算出现的百分比,而无需再次计数?另外,我对SQL不是很了解,但是如果
log\u hash
列被索引会更好吗?

你确定这就是问题所在吗?我认为文本处理更有可能导致效率低下。在序列化程序端这样做可能更有意义。毕竟,如果
计数(…)
真的是慢的部分,它最多会使查询所花费的时间增加一倍。老实说,我真的不知道问题是否在于文本处理,也许你是对的。我将删除文本处理,只输出25.0和50.0作为浮动。不管怎样,我的问题还是站着不动。有可能重用计数吗?此外,看起来更应该构造一个索引(这里最好是
ForeignKey
),以避免
groupby
变慢。不,这是不可能的,目前Django的ORM不够聪明,无法实现这一点,并且到处重复子查询