Timofey Trofimov
Timofey Trofimov

Reputation: 1174

Django aggregate with expressions between ForeignKey (and not) values

I'm having these models:

class Car(models.Model):
  liter_per_km = models.FloatField(default=1.0)
  
class DrivingSession(models.Model):
  car = models.ForeignKey(Car, on_delete=models.CASCADE)
  km = models.FloatField(default=1.0)

Is there a way using Django features (e.g aggregate) to calculate the same total_liters like in code below?

total_liters = 0.0
for session in DrivingSession.objects.all():
  total_liters += (session.km * session.car.liter_per_km)

Upvotes: 1

Views: 42

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can work with:

from django.db.models import F, Sum

DrivingSession.objects.aggregate(
    total_liters=Sum(F('car__liter_per_km') * F('km'))
)

This will thus multiple the number of kilometers of that DrivingSession with the liter_per_km for that car.

Upvotes: 1

Related Questions