I make a filtered query to my model ProductList, but the filter parameters are in another model, so I do the following, first the model:
class ListaProductosVenta(models.Model):
producto = models.ForeignKey('Producto',related_name='lpv_pr',on_delete=models.CASCADE)
venta = models.ForeignKey('Venta',related_name='lvp_v',on_delete=models.CASCADE)
cantidad = models.PositiveSmallIntegerField()
precio = models.DecimalField(decimal_places=2, max_digits=8)
precioTotal = models.DecimalField(decimal_places=2, max_digits=8)
class Venta(models.Model):
cliente = models.ForeignKey('Cliente',related_name='v_cl',on_delete=models.CASCADE,null=True)
vendedor = models.ForeignKey('Usuario',related_name='v_u',on_delete=models.CASCADE)
tienda = models.ForeignKey('Tienda',related_name='v_ti',on_delete=models.CASCADE)
formaPago = models.CharField(choices=constants.formaDePago,max_length=1)
tipoPrecio = models.CharField(choices=constants.tipoVenta,max_length=1)
fecha = models.DateField()
total = models.DecimalField(decimal_places=2, max_digits=8, null=True)
descripcion = models.TextField(null=True)
And this is my serializer:
class VentaSerializerLPV(serializers.ModelSerializer):
tienda = TiendaSerializerProperties(read_only=True)
cliente = ClienteSerializer(read_only=True)
vendedor = UsuarioSerializer(read_only=True)
class Meta:
model = Venta
fields = ('id','cliente','vendedor','tienda','formaPago','fecha')
class ListaProductosVentaSerializer(serializers.ModelSerializer):
producto = ProductoSerializer(read_only=True)
venta = VentaSerializerLPV(read_only=True)
class Meta:
model = ListaProductosVenta
fields = ('id','venta','producto','cantidad','precio','precioTotal')
and this is the query I made:
@api_view(['GET'])
def vendedorMasDineroL(request,index, fi, ff):
vendedores = ListaProductosVenta.objects.filter(venta__fecha__range(fi,ff)).filter(venta__vendedor__tienda__exact=index).annotate(sum_total=Sum('precioTotal'), n_venta=(Count('venta__vendedor__id')))
serializer = ListaProductosVentaSerializer(vendedores)
return Response(serializer.data)