P
P
paevlk20072014-07-08 01:08:03
Django
paevlk2007, 2014-07-08 01:08:03

Django - how to override save method?

Hey!!!

class Accessories(models.Model):
    created_on =  models.DateTimeField(u"Дата создания", auto_now_add=True, editable=True, blank=True, null=True)
    access_date_perfor = models.DateField(u"Дата выполненной работы", blank=True, null=True)
    ac_start = models.TimeField(u"С", blank=True, null=True)
    ac_end = models.TimeField(u"По", blank=True, null=True)
    ac_total = models.CharField(u"total", max_length=10, blank=True, null=True)
    ac_activates = models.BooleanField(u"Выполнено", default=False)

There is a function that calculates the number of hours:
def period_duration(self):
        total_seconds = (
            (self.ac_end.hour*3600
             +
             self.ac_end.minute*60
             +
             self.ac_end.second
            )
            -
            (self.ac_start.hour*3600
             +
             self.ac_start.minute*60
             +
             self.ac_start.second)
        )
        hour, total_seconds = divmod(total_seconds, 3600)
        minute, total_seconds = divmod(total_seconds, 60)
        return "%02d:%02d" % (hour, minute)

How to override the save method so that the function (or not the function, but the calculation process itself) calculates def period_duration and writes the values ​​\u200b\u200binto the field
ac_total =              models.CharField(u"total", max_length=10, blank=True, null=True)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey K, 2014-07-08
@paevlk2007

def save(self, *args, **kwargs)
    self.ac_total = self.period_duration()
    super(Accessories, self).save(*args, **kwargs)

But it's better to do this:
from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=Accessories)
def calc_ac_total(sender, instance, **kwargs):
    instance.ac_total = instance.period_duration()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question