In the database I have these values
INSERT INTO 'principal_ingresos' ('id', 'instalacion_id', 'natural', 'juridico', 'fecha') VALUES
(1, 1, 1066, 0, '2017-01-04'),
(2, 1, 754, 0, '2017-02-08'),
(3, 1, 1253, 0, '2017-03-09'),
(4, 2, 2504, 0, '2017-01-04'),
(5, 2, 1551, 0, '2017-02-02'),
(6, 2, 3078, 0, '2017-03-08'),
and I want to know the sum for installation of the legal and natural fields for this I make the following query
ingjur =ingresos.objects.filter(pk=id_instalacion).values('natural').annotate(sum=Sum('natural'))
I use this url to general a profile for each installation where I should show the result:
url(r'^detalle_inst/(?P<id_instalacion>\d+)$','principal.views.detalle_inst'),
But I realize that when it shows the result instead of adding all the natural values of the same installation, for example with id=1
, I go through the table that is:
The installation 1 as a natural result shows me the first natural value of the table, that is, 1066
and not the sum of all the natural values of that installation.
The installation 2 shows the 2nd value of the table: 754
and not the sum of the installation with id two.
It must be a problem in the query, but I do not realize where ...
template.html
<div class="col-md-3">
<div class="app-widget-tile app-widget-tile-info">
<div class="intval intval-lg">
$ {{ ing.sum|floatformat:"2"|intcomma }}
</div>
<div class="line">
<div class="title wide text-center">Total Ingresos Naturales</div>
</div>
</div>
</div>
view.py
def detalle_jc(request, id_jovenclub ):
jc = jovenclub.objects.get(pk=id_jovenclub)
datos=ingresos.objects.all()
print jc.ingresos_set.all()
ing=0
ing = ingresos.objects.filter(pk=id_jovenclub).values('jovenclub_id').annotate(sum=Sum('natural'))
ingjur =ingresos.objects.values('jovenclub_id').annotate(sum=Sum('juridico'))
sum=0
for ingreso in jc.ingresos_set.all():
sum=ingreso.get_importe()
sum=(round((sum/jc.plan_gral)*100,2))
return render_to_response( 'perfil_jc.html', { 'ingjur':ingjur[0], 'ing':ing[0] , 'jc': jc, 'porciento':sum, 'datos':datos}, context_instance=RequestContext(request))