Best way for grouping models by two week periods and tie them to a data entry?

I am working on a project that is based on a two week time period. I have a model with a start_date and end_date as seen below:

class CreateNewTimesheet(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    start_date = models.DateField(_("Start Date"))
    end_date = models.DateField(_("End Date"))
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

I want to be able to add another line or something that groups the start_date and end_date.


Dates: 03/06/2024 - 03/16/2024

And group or tie that to "week 1".

The purpose behind this is to create a timesheet based on a two week time period. I need to be able to group the timesheets by a two week period and tie them to that specific group. All of the Timesheets need to be stored.

After start_date and end_date are entered I need them to be tied to week one. I was thinking about adding another line to the CreateNew model and then tie that to week one. And then each start_date and end_date are entered, a new "week" is entered for each new start_date and end_date is created. Should that be based off of created_at entry? Should each week be grouped by a new url?

I am honestly stuck at this point about both grouping by two weeks and then tying to a new week.

try creating a new model TwoWeekPeriod to represent the two-week periods.

the week_number is calculated based on the start date and the new TwoWeekPeriod is created or retrieved based on the start and end dates.

from django.db import models
from django.utils import timezone

class TwoWeekPeriod(models.Model):
    start_date = models.DateField(_("Start Date"))
    end_date = models.DateField(_("End Date"))
    week_number = models.IntegerField(_("Week Number"))

class CreateNewTimesheet(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    start_date = models.DateField(_("Start Date"))
    end_date = models.DateField(_("End Date"))
    two_week_period = models.ForeignKey(TwoWeekPeriod, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        week_number = (self.start_date - timezone.now().date()).days // 14 + 1
        two_week_period, _ = TwoWeekPeriod.objects.get_or_create(
            start_date=self.start_date,
            end_date=self.end_date,
            defaults={'week_number': week_number}
        )
        self.two_week_period = two_week_period
        super().save(*args, **kwargs)
Back to Top