Python - Django - Filter and count all people in first year from start date

Viewed 64

I need to count all the people who are in the first year of the contract. I even made several attempts and failed. Can anyone help me? Thanks!

Model:

class Contracts(models.Model):
    person = models.CharField(max_length=50, null=True, blank=True, verbose_name='Name')
    start_date = models.DateField(null=True, blank=False, verbose_name='Start')

    def __str__(self):
        return '{}'.format(self.person)

So far...

View:

def people_in_first_year(request):
    people = Contracts.objects.filter(Q(start_date__lte=timezone.now()) & Q(end_date__gte=timezone.now() + timedelta(days=365)))
    total_people = people.count()

    context = {
        'total_people': total_people,
    }

    return render(request, 'people.html', context)
1 Answers

Since there is not an end_date, you can not filter much on that one. What you can do is simply set the start_date to be greater than or equal to now minus 365 days:

total_people = Contracts.objects.filter(
    start_date__gte=timezone.now() - timedelta(days=365)
).count()

A year however is not per se 365 days. You can for example make use of the python-dateutil package [pypi], and work with a relativedelta [readthedocs.io]:

from dateutil.relativedelta import relativedelta

total_people = Contracts.objects.filter(
    start_date__gte=timezone.now() - relativedelta(years=1)
).count()
Related