Show Queries with ORM grouped by a field and SUM for each TYPE in DJANGO

0

Very good, I have records in my DATABASE in POSTGRES and from Django ORM I try to make a query: Each record has a COST and TYPE field, and there may be N record of only one type with different prices. What I want is to bring, the sum of the COSTS GROUPED by TYPES; As you can see in the Image, I have in the Database 6 records and grouped I would throw only 3 records with their respective SUMMARY. I tried doing with ANNOTATE and SUM but without success, how can the query be efficiently done? thanks

Try doing so

consulta = Venta.objects.all().annotate(totalp=Sum(F('costo'), 
           output_field=models.FloatField()))

But it does not bring me grouped

    
asked by Alex Ancco Cahuana 12.07.2017 в 23:14
source

1 answer

1

A little late the answer: P

 consulta = Venta.objects.all().values('tipo')
            .annotate(totalp=Sum(F('costo'),
             output_field=models.FloatField()))

Greetings, if you still read this.

    
answered by 12.12.2018 в 18:50