Django, query summation of one table to another connected to the foreigner

0

I have the following models:

class Articulo(models.Model):
   nombre = models.CharField(max_length=80)
   costo = models.DecimalField(max_digits=6, decimal_places= 2)
   precio = models.DecimalField(max_digits=6, decimal_places= 2)   
   familia = models.ForeignKey(Familia)

def unidades(self):
    n = self.Movimiento.all().count()
    return str(n)

class Movimiento(models.Model):
    articulo = models.ForeignKey(Articulo)
    almacen = models.ForeignKey(Almacen)
    entidad = models.ForeignKey(Entidad)
    descripcion = models.CharField(max_length=70)
    entrada = models.DecimalField(max_digits=5, decimal_places=2, default=0.0)
    salida = models.DecimalField(max_digits=5, decimal_places=2, default=0.0)
    costo = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True, default=0.0)
    precio = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True, default= 0.0)
    importe = models.DecimalField(max_digits=5, decimal_places=2, default=0)

What I really want the def units of the Article to say is the subtraction of units of all the movements of its article (input - output)

I have put the count () test, but all fail.

    
asked by Cecilior 25.10.2016 в 18:21
source

1 answer

0

This is a way to do it using native python functions. Remember that to access the set of instances that refer you, you must use class_set where class is the name of the model referer . Then it would be self.movimiento_set.all()

def unidades(self):
    movimientos = self.movimiento_set.all()
    unidades = sum(map(lambda m: m.entrada - m.salida, movimientos))
    return unidades
    
answered by 25.10.2016 / 18:29
source