Reputation: 129
class TimecardModel(models.Model):
latitude = models.FloatField(max_length=16, blank=True, null=True)
longitude = models.FloatField(max_length=16, blank=True, null=True)
employee = models.ForeignKey(User)
clock_in = models.DateTimeField(blank=True, null=True, editable=True)
clock_out = models.DateTimeField(blank=True, null=True)
is_clocked_out = models.BooleanField(blank=True, default=False)
I want to set is_clocked_out = True everytime when employee clock_out, how do I achieve this thing. I know that django singals can do the job, but can I write method on django model to do this. If I write one how this method will execute everytime emplyee clock_out. Do I need to call this or it will work everytime I save the model object. Will @property help me? then how? Thanks in advance.
Upvotes: 0
Views: 127
Reputation: 7049
You can create a method which clocks out, and changes is_clocked_out
. This will be less complicated than overriding the model’s save()
method.
def clockout(self):
self.clock_out = timezone.now()
self.is_clocked_out = True
self.save()
return self.is_clocked_out
And then you can just clock out by calling this code via instance.clockout()
To override the .save()
method, you can do this:
def save(self, *args, **kwargs):
if self.clock_out:
self.is_clocked_out = True
super(TimecardModel, self).save(*args, **kwargs)
Upvotes: 2