Задать вопрос

Тел: +7 965 3737 888

445

Просмотров

0

Ответов

Custom model field for mysql time type.

<p>Django does not have a suitable model field can process time type in mysql, the DateTimeField built-in django can not process more than 24 hours. That's why the code born.</p>
<p><strong>Simply usage</strong>
`from myapp.models import TimeAsTimeDeltaField, SECONDS_PER_MIN, SECONDS_PER_HOUR, SECONDS_PER_DAY</p>
<p>class EstimatedTime:
    days = None
    hours = None
    minutes = None
    seconds = None</p>
<p>class Case(models.Model):
    estimated_time = TimeAsTimeDeltaField(null=True, blank=True)</p>
def get_estimated_time(self):
    estimated_time = EstimatedTime()
    if self.estimated_time:
        total_seconds = self.estimated_time.seconds + (self.estimated_time.days * SECONDS_PER_DAY)

        days = total_seconds / SECONDS_PER_DAY
        hours = total_seconds / SECONDS_PER_HOUR - days * 24
        minutes = total_seconds / SECONDS_PER_MIN - hours * 60 - days * 24 * 60
        seconds = total_seconds % SECONDS_PER_MIN

        estimated_time.days = days
        estimated_time.hours = hours
        estimated_time.minutes = minutes
        estimated_time.seconds = seconds

        return estimated_time
    else:
        return estimated_time

Вопрос полезен? Да0/Нет0
file_3195.py(1.6Кб)
None