Home > Mobile >  How to Count quantity of my QuerySet. Django
How to Count quantity of my QuerySet. Django

Time:02-02

Well, i have the following function:

employees_birthday = Employees.objects.filter(EmployeeDataNasc__gte=first_day, EmployeeDataNasc__lte=last_day)

It serves to return employees born between the dates. She returns:

<QuerySet [<Employees: Alberto Santos>, <Employees: Josney Arman>]>

But, I would just like to display the number of employees in the QuerySet, i.e. make a Count function.

Can someone help me with the syntax?

CodePudding user response:

You can use the .count() method on a queryset to get the number of items in the queryset. Here's the updated code:

employees_birthday = Employees.objects.filter(EmployeeDataNasc__gte=first_day, EmployeeDataNasc__lte=last_day)

employee_count = employees_birthday.count()

In this example, employees_birthday is the queryset containing all employees born between the given dates. The .count() method returns the number of items in the queryset, which is stored in the variable employee_count.

You can then use the employee_count variable in your code to display the number of employees, for example:

print("Number of employees born between {} and {}: {}".format(first_day, last_day, employee_count))

CodePudding user response:

If you are going to display the Employees anyway, then it is better to use len(…). This will fetch the Employees in memory, and return the number of Employees:

employees_birthday = Employees.objects.filter(
    EmployeeDataNasc__range=(first_day, last_day)
)
number_of_birthdays = len(employee_birthdays)

if you however plan to only render the number of Employees, then you use .count() [Django-doc], since this will prevent fetching the items in memory.

  • Related