Query two or more tables

0

I need to obtain the price of the type to which the vehicles belong in order to add them and register them in the Rental Model

class Tipo(models.Model):
   descripcion = models.CharField(max_length=100)
   precio = models.DecimalField(max_digits=20,decimal_places=2,default=Decimal('0.00'))
   km_mantenimiento = models.DecimalField(max_digits=20,decimal_places=2,default=Decimal('0.00'))
   def __str__(self):
       return self.descripcion

class Vehiculo(models.Model):
   placa = models.CharField(primary_key=True,max_length=100)
   descripcion = models.CharField(max_length=100)
   marca = models.CharField(max_length=100)
   modelo = models.CharField(max_length=100)
   cilindrada = models.CharField(max_length=100)
   tipo = models.ForeignKey(Tipo)
   km_recorrido = models.DecimalField(max_digits=20,decimal_places=2,default=Decimal('0.00'))
   activo = models.BooleanField(default=True)
   def __str__(self):
       return self.descripcion

class Alquiler(models.Model):
   fecha = models.DateTimeField(auto_now_add = timezone.now())
   hora_inicio = models.TimeField()
   hora_fin = models.TimeField()
   cajero = models.ForeignKey(User)
   cliente = models.ForeignKey(Cliente)
   vehiculos = models.ManyToManyField(Vehiculo)
   #total = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal('0.00'))
   class Meta:
       permissions = (
        ("add_alquileres", "Puede crear Alquileres"),
       )
   def __int__(self):
       return self.cliente
   def motos(self):
       return ', '.join([Vehiculo.descripcion for Vehiculo in self.vehiculos.all()])
    
asked by Jhon Vargas 20.10.2017 в 02:32
source

2 answers

1

You find the price here:

v = Vehiculo.object.get(pk=xxx)
v.tipo.precio

See the documentation: link

    
answered by 20.10.2017 в 02:56
0

Try with:

from django.db.models import Sum

Vehiculo.objects.filter(attr=xxx).aggregate(Sum('tipo__precio'))

You should have a sum of all the vehicle prices with respect to your filter .filter(attr=xxx)

    
answered by 21.10.2017 в 00:15