更改Django管理员中持续时间字段的格式

时间:2018-08-09 15:14:33

标签: django django-models django-admin

我在模型中使用django DurationField来计算两个DateTimeField之间的时间差。

在该模型的管理站点上,该字段显示如下:

# short duration
Cumulative Total time:   0:51:33
# longer duration
Cumulative Total time:   2 days, 3:10:21

是否可以将此字段的格式更改为以下给定格式?

Cumulative Total time:   2 days, 3 hours, 10 minutes, 21 seconds

2 个答案:

答案 0 :(得分:1)

DurationField具有与格式相关的以下代码:

...
from django.utils.duration import duration_string
...

class DurationField(Field):
    ...
    def value_to_string(self, obj):
        val = self.value_from_object(obj)
        return '' if val is None else duration_string(val)

函数duration_string如下所示:

def duration_string(duration):
    """Version of str(timedelta) which is not English specific."""
    days, hours, minutes, seconds, microseconds = _get_duration_components(duration)

    string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
    if days:
        string = '{} '.format(days) + string
    if microseconds:
        string += '.{:06d}'.format(microseconds)

    return string

一种解决方案是创建可覆盖上述一种方法的自定义字段:

from django.utils.duration import _get_duration_components

class CustomDurationField(DurationField):
    def value_to_string(self, obj):
        val = self.value_from_object(obj)
        if val is None:
            return ''

        days, hours, minutes, seconds, microseconds = _get_duration_components(val)
        return '{} days, {:02d} hours, {:02d} minutes, {:02d}.{:06d} seconds'.format(
            days, hours, minutes, seconds, microseconds)

您需要调整精确的输出以符合您的要求。

答案 1 :(得分:0)

如果您使用 SerializerDurationField,则必须将 value_to_string() 更改为 to_representation()

class DurationField(Field):
    ...
    def to_representation(self, value):
       return duration_string(value)

其中 duration_string() 的实现与上述相同