如何在Django ORM中创建过滤数据的注释?

时间:2009-10-14 16:57:09

标签: django django-orm django-aggregation

我有以下型号:

class ApiUser(models.Model):
    apikey = models.CharField(max_length=32, unique=True)


class ExtMethodCall(models.Model):
    apiuser = models.ForeignKey(ApiUser)
    method  = models.CharField(max_length=100) #method name
    units   = models.PositiveIntegerField()    #how many units method call cost
    created_dt = models.DateField(auto_now_add=True)

对于报告,我需要获取今天进行任何通话的所有用户以及每位用户的所有通话的总费用。

在SQL中,这将是:

SELECT apiuser.*, q1.total_cost
FROM apiuser INNER JOIN (
    SELECT apiuser_id, sum(units) as total_cost
    FROM extmethodcall
    WHERE create_dt = curdate()
    GROUP by apiuser_id
) USING apiuser_id

到目前为止,我找到了以下解决方案:

models.ExtMethodCall.objects.filter(created_dt=datetime.date.today()).values('apiuser').annotate(Sum('units'))

返回apiuser_idunits__sum

还有更智能的解决方案吗?

0 个答案:

没有答案