1

My Views.py code

class ListaFuncionariosView(ListView):
    model = Funcionarios
    template_name = '../templates/funcionarios/lista_funcionarios.html'
    paginate_by = 10
    ordering = ['FuncionarioCartao']
    queryset = Funcionarios.objects.filter(EmpresaCodigo=1)
    funcionarios_number = Funcionarios.objects.aggregate(Count('FuncionarioCartao'))
    

My HTML

<h1>Good Morning</h1>
   Exists: {{funcionarios_number}}
    <br>
    {{funcionarios}}

I would like to show the total number of registered employees in my db table (in the HTML file below), but I don't know how to put variables in class based views, in this case ListView. I'm using 4.0 Django

I tried put: funcionarios_number = Funcionarios.objects.aggregate(Count('FuncionarioCartao')) in bellow of my class, but this is not showed in my html.

1 Answer 1

1

By aggregating at the class-level, the query will run when you start the server, and the count will thus always remain that exact number.

You can define this in a function:

class ListaFuncionariosView(ListView):
    model = Funcionarios
    template_name = '../templates/funcionarios/lista_funcionarios.html'
    paginate_by = 10
    ordering = ['FuncionarioCartao']
    queryset = Funcionarios.objects.filter(EmpresaCodigo=1)

    def funcionarios_number(self):
        return Funcionarios.objects.aggregate(total=Count('FuncionarioCartao'))[
            'total'
        ]

and then access the function in the view in the template:

{{ view.functionarios_number }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.