Django ORM Left Join With GROUP BY and SUM

2019-07-22 02:34发布

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条回答
【Aperson】
2楼-- · 2019-07-22 03:22
User.objects.filter(user_type=type).values('id').annotate(total_time=Sum(useraction__time))
查看更多
登录 后发表回答