如何在 Django ORM 中对过滤数据创建注释?
我有以下模型:
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_id
和 units__sum
。
还有更智能的解决方案吗?
I have the following models:
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)
For report, i need to get all users who made any call today and total cost of all calls for each user.
In SQL, that would be something like:
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
So far, i have found the following solution:
models.ExtMethodCall.objects.filter(created_dt=datetime.date.today()).values('apiuser').annotate(Sum('units'))
which returns me apiuser_id
and units__sum
.
Is there any more intelligent solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这是最自然的解决方案,Django ORM 会将
.annotate(Sum('units'))
转换为 SQL
SELECT ... sum(units) asunits__sum
No this is the most natural solution, Django ORM will "tanslate"
.annotate(Sum('units'))
into SQL
SELECT ... sum(units) as units__sum