Django ORM Left Join With GROUP BY and SUM

我的未来我决定 提交于 2019-12-24 04:16:17

问题


I am using Django 1.8.

I have a User model and a UserAction model. A user has a type. UserAction has a time, which indicates how long the action took. They look like this:

class User(models.Model):
   user_type = models.IntegerField()

class UserAction:
   user = models.ForeignKey(User)
   time = models.IntegerField()

Now what I want to do is get ALL users of a certain type along with the sum of the time of their actions.So it would look something like this:

{user:1,total_time=5000}, {user:2,total_time=230}, {user:3,total_time=0}

Given I have the required type in a var called type, what I am doing is:

UserAction.objects.filter(user__type=type)
.values('user').annotate(total_time=Sum(time))

This almost does what I need it to however it does not include users of the given type that don't have any UserAction associated with them, in that case I would want the total_time to just be 0. I've been doing some searching but am not quite sure how I would do this. I know how I would do it in raw SQL(just do a left join) but the Django ORM is still pretty new to me. Could anyone point me in the right direction here? Any advice would be appreciated, thanks much!


回答1:


User.objects.filter(user_type=type).values('id').annotate(total_time=Sum(useraction__time))


来源:https://stackoverflow.com/questions/30677459/django-orm-left-join-with-group-by-and-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!