How to get last six month data from date field – django

Question:

I do have a model as below

class Employee(models.Model):
    employee_name = models.CharField(max_length=100)
    joining_Date = models.DateField(blank=False, null=False)

I want to get data for last six months (including current month) joined employee count month wise.

Example:

July : 12,
June : 10,
May : 8,
April : 16,
March : 13,
February : 10,

joining_Date stores data like "2022-07-22". How to get done this by having date field?

Asked By: Saravanan Ragavan

||

Answers:

You can try to find maximum apropriate date, and filter by it

from datetime import date
from dateutil.relativedelta import relativedelta


def find_employee(request):
    today = date.today()
    six_months = today - relativedelta(months=6)
    emloyed_for_six_month = Employee.objects.filter(joining_Date__gte = six_months)

Your employee model should be named with a capital letter. It is conventional
https://stackoverflow.com/a/386054/14632651

Answered By: oruchkin

To get the count of new employees per month you will need to annotate and use Trunc to just get the month, see below:

from datetime import date
from dateutil.relativedelta import relativedelta

from django.db.models.functions import Trunc

six_months_ago = date.today() + relativedelta(months=-6)

employees_per_month = Employee.objects.filter(join_date__gte=six_months_ago)
   .annotate(
      joining_month=Trunc('joining_date', 'month', output_field=DateField())
   ) 
   .order_by('joining_month') 
   .values('joining_month') 
   .annotate(employees=Count('joining_month'))

This will give you a queryset with the following structure:

<QuerySet [{'joining_month': datetime.date(2022, 6, 1), 'employees': 2},
    {'joining_month': datetime.date(2022, 7, 1), 'employees': 1}, ...

Edit
To convert the QS into a flat dict:

employee_count_dict = {}
for employee_count in employees_per_month: 
   employee_count_dict[val['joining_month']] = val['employees']
Answered By: 0sVoid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.