Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

524
Vistas
Summing columns in Django with related fields

I'm trying to do some aggregation on some of my Django columns, but I'm getting an error I can't figure out. Here are my models (the relevant stuff anyways):

class Fillup(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    date = models.DateField(default=date.today)
    trip_distance = models.FloatField(validators=[MinValueValidator(0.0)])
    car = models.ForeignKey('Car',on_delete=models.CASCADE, related_name='fillups')


class Car(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    name = models.CharField(max_length=25)

So each Fillup object is essentially a tank of gas in a car, and what I want to do is get the total of the trip_distance column for each car. I've tried several things from various other StackOverFlow pages, but nothing seems to work.

My first attempt was this adding this field to the Car Model:

@property
def distance_driven(self):
    return self.fillups.aggregate(sum('trip__distance'))

But I just get the following error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

I also tried adding this to my serializer, but got the same error:

distance_driven = serializers.SerializerMethodField()

def get_distance_driven(self, ob):
    return ob.fillups.all().aggregate(sum('trip_distance'))['trip__distance']

Is there something I'm missing here? I don't understand why I'm getting that error when trying to sum a FloatField column.

Any help would be greatly appreciated!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

In order to aggregate, you use a Sum object [Django-doc], not the Python builtin sum.

You can obtain the sum of a single object with:

from django.db.models import Sum

return self.fillups.aggregate(total=Sum('trip_distance'))['total']

If you have to do this for multiple records, it is better to .annotate(…) [Django-doc]:

from django.db.models import Sum

Car.objects.annotate(
    total_distance=Sum('fillups__trip_distance')
)

The Car objects that arise from this queryset will have an extra attribute .total_distance with the sum of the related Fillup trip_distances.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda