Django queryset, calculate subtraction of two numbers

2

I have the following model:

class MyClass(models.model):
    usuario = models.Charfield(max_length=45)
    saldo_ini=models.DecimalField(decimal_places=1,max_digits=10, null=True)
    saldo_fin=models.DecimalField(decimal_places=1,max_digits=10, null=True)

In a view I want to get the usuario and the subtraction of saldo_fin - saldo_ini using a queryset. How I do this?

I tried this:

MyClass.objects.values('usuario').annotate(resta=float('saldo_fin') - float('saldo_ini'))
    
asked by juan muñoz 25.07.2017 в 00:10
source

1 answer

2

For these cases you can use expressions F () which allow you to reference columns of a specific model.

For example, in the following query we are looking for books whose amount of likes is greater than the number of pages of it (both likes and numero_paginas are field of the model):

>>> Libro.objects.filter(likes__gt=F('numero_paginas'))

For your case you could use:

>>> from django.db.models import F
>>> MyClass.objects.values('usuario').annotate(resta=F('hodometro_llegada') - F('hodometro_salida'))
    
answered by 25.07.2017 / 00:53
source