Problems with query in django


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:


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 ...


<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 class="line">
<div class="title wide text-center">Total Ingresos Naturales</div>

def detalle_jc(request, id_jovenclub ):
jc = jovenclub.objects.get(pk=id_jovenclub)
print jc.ingresos_set.all()
ing = ingresos.objects.filter(pk=id_jovenclub).values('jovenclub_id').annotate(sum=Sum('natural'))

ingjur =ingresos.objects.values('jovenclub_id').annotate(sum=Sum('juridico'))
for ingreso in jc.ingresos_set.all():

return render_to_response( 'perfil_jc.html', { 'ingjur':ingjur[0], 'ing':ing[0] , 'jc': jc, 'porciento':sum, 'datos':datos}, context_instance=RequestContext(request))
asked by Roly Miranda Díaz 03.05.2017 в 15:48

2 answers


What I can analyze is the following:

in your the variable "ing" returns a single value, since you compare the "pk" with "id_jovenclub" , being that you should compare "install_id" with "id_jovenclub" and then make the sum of "natural"

It should be something like this:

ing = ingresos.objects.filter(instalacion_id=id_jovenclub).values('jovenclub_id').annotate(sum=Sum('natural'))

I hope it's helpful

answered by 04.05.2017 / 14:46

Try this query

ingjur = ingresos.objects.filter(pk=id_instalacion).aggregate(sum=Sum('natural'))
answered by 04.05.2017 в 18:58