How Calculate Hours and OT Hours, save to database?

I'm trying to calculate login and logout and convert it into total hours. If the time exceeds 9 hours it should then calculate OThours. Then save both total hours and OThours into my model. How can I go around this? I know it's by using property but I'm not sure how to get the syntax right with this.

I just need some advice and insight on what to do, any help is appreciated TIA.

Here is my code:

testuser = models.ForeignKey(User,on_delete = models.CASCADE,unique_for_date= 'reportDate')
status = models.CharField(max_length=30, choices=STATUS_CHOICES,null=True)
reportDate = models.DateField(blank=False, null=False)
login = models.TimeField(blank=False, null=False)
logout = models.TimeField(blank=False, null=False)
totalHours = models.DecimalField(max_digits=4,decimal_places=2,null=True)
OTHours = models.DecimalField(max_digits=4,decimal_places=2,null=True)
mainTasks = models.CharField(max_length=50, blank=False, choices=TASKS_CHOICES, null=True)
remarks = models.CharField(max_length=30,null=True)

def __str__(self):
    return f'{self.testuser.full_name} DPR Log'

@property
def CalculateTotalHours(self):
    self.totalHours = self.logout.timeDelta - self.login.TimeDelta
    return self.TotalHours

@property
def OTHours(self):
    if self.totalHours > 9.00:
        self.OTHours = self.totalHours-9.00

Upvotes: 0

Views: 71

Answers (1)

schillingt
schillingt

Reputation: 13731

I would not use a property to change the instance. That's a poor interface as most users expect a property to simply read and return data.

Here's what I'd do:

class MyModel(models.Model):

    @classmethod
    def calculate_hours(cls, instance):
        total_hours = instance.logout.timedelta - self.login.timedelta
        ot_hours = None
        if total_hours > 9:
            ot_hours = total_hours - 9.00
            total_hours = 9.00
        return total_hours, ot_hours

# Then to use it:
instance = MyModel.objects.get(something)
instance.total_hours, instance.ot_hours = MyModel.calculate_hours(instance)
instance.save()

Upvotes: 1

Related Questions