Django querying data out of models and get sum of field

Issue

I’m just beginning with Django and have the following question:
I have set up a model looking like

class Automation_Apps(models.Model):
    app_name = models.CharField(max_length=50)
    app_description = models.TextField(blank=True)
    view_function_name = models.CharField(max_length=50)
    time_saver_min = models.IntegerField()
    implementation_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.app_name

class Automation_Usage(models.Model):
    used_app = models.ForeignKey(Automation_Apps, on_delete=models.CASCADE)
    used_by_user = models.ForeignKey(User, on_delete=models.CASCADE)
    used_on_date = models.DateTimeField(auto_now_add=True)

I would like to query it like:

Select Sum(time_saver_min)
from Automation_Apps, Automation_Usage
where Automation_Usage.used_app = Automation_Apps.app_name

The goal of this is the following:
Automation_App will have the Apps and a field, how much time will be saved by using this app

Automation_Usage will have the records, when a user is utilizing the app.

With my query I would like to pull how often the apps where used and how much time was saved by using it (which comes from the Automation_App).

I would like to do this in my view.

Solution

To get sum of time utilized over all apps by each user:

from django.db.models import Sum
Automation_Usage.objects.values('used_by_user').annotate(time=Sum('used_app__time_saver_min'))

To get number of users and sum of time utilized for each app:

from django.db.models import Sum, Count
Automation_Usage.objects.values('used_app').annotate(users=Count('used_by_user'), time=Sum('used_app__time_saver_min'))

Answered By – kamran890

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published