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.
CodePudding user response:
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 }}