[Answered ]-Sum of values ​in Django views

1👍

updated:
values() returns a Queryset that behaves similar to a dict. Simply try

=conta1['contar'] + 1
or
=conta[0]['contar']

to debug print(conta) and you will see it

please add the error trace in future posts

0👍

You can determine the maximum contar and then increment this with one, like:

from django.db.models import Max


def atualizar(request, contador):
    lista = factura.objects.filter(contador__contador=contador)
    conta = lista.aggregate(max_contar=Max('contar'))['max_contar'] or 0
    cont = get_object_or_404(cliente, contador=contador)
    if request.method == 'POST':
        data1 = request.POST['data1']
        factura_nr = request.POST['factura_nr']
        data2 = request.POST['data2']
        consumo = request.POST['consumo']
        dados = factura.objects.create(
            contador=cont,
            contar=conta + 1,  # to incremet here
            consumo=consumo,
            data1=data1,
            data2=data2,
            factura_nr=factura_nr,
        )
        return redirect('name-of-some-view')

    return render(
        request, 'tabela.html', {'lista': lista, 'cont': cont, 'conta': conta}
    )

Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from factura to Factura.


Note: It is better to use a Form [Django-doc]
than to perform manual validation and cleaning of the data. A Form will not
only simplify rendering a form in HTML, but it also makes it more convenient
to validate the input, and clean the data to a more convenient type.


Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.


Note: In case of a successful POST request, you should make a redirect
[Django-doc]

to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Leave a comment