Oliver Demus
Oliver Demus

Reputation: 13

Django querying data out of models and get sum of field

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.

Upvotes: 1

Views: 114

Answers (3)

Simon Vu
Simon Vu

Reputation: 46

You can use annotate in Django ORM.

My solution:

Sum(time_saver_min) based on Automation_Usage.used_app = Automation_Apps.app_name

=> queryset = Automation_Usage.objects.values('used_app').annotate(Coalesce(Sum('used_app__time_saver_min'), Value(0)))

=> print(queryset['used_app__time_saver_min__sum'])

Upvotes: 1

kamran890
kamran890

Reputation: 842

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'))

Upvotes: 1

samkayz
samkayz

Reputation: 97

You can use the Model Sum to Sum the value of your model.

Do it this way;

from django.db.models import Sum Then

data = Model.objects.aggregate(Sum('time_saver_min'))['time_saver_min__sum'] print(data)

Upvotes: 1

Related Questions