Home > front end >  Django aggregate with expressions between ForeignKey (and not) values
Django aggregate with expressions between ForeignKey (and not) values

Time:07-13

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)

CodePudding user response:

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.

  • Related