0
Hello, everybody. I have a Django project and one of its features is to generate statistical numbers. For example: I have an employee model and it has boolean fields, like, whether it is active or not, present or not, etc. So I want to show in the template a card containing the total number of registered employees and how many of these are active and on a given day how many were present, etc. That is, the quantity will be shown according to the state of the object, whether true or false. Check out an example model: py.models
class Funcionario(models.Model):
nome = ...
ativo = models.BooleanField()
...
py views.
from .models import Funcionario
class IndexView(TemplateView): # TemplateView mesmo
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['funcionarios'] = Funcionario.objects.all()
return context
I know it’s easy to show the total in the template using {{ functionalities.Count }} or {{ functionalities|length }}. But I still don’t really understand the difference between the two modes. However, my question is about how to show the number of active and inactive employees. Some alternatives I thought was to create several keys in def get_context_data:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['funcionarios'] = Funcionario.objects.all()
context['funcionarios_ativos'] = Funcionario.objects.filter(ativo=True)
context['funcionarios_inativos'] = Funcionario.objects.filter(ativo=False)
...
return context
Or you could create @propety in the Funcio model; or you could create custom tags. Finally, I would like an opinion on what would be the most appropriate way to do this.
Thank you in advance.
Creates a
managerto theFuncionarioin your models. (FunicionarioManager(models.Manager)). Within it create the method that will count forativo. If you have any questions about how to do it, text.– Paulo Marques
Excellent suggestion, Paulo Marques. Thank you very much.
– douglas1alc