Я думаю, вам нужно что-то вроде этого (непроверенный код) ::
import datetime
from django.db import models
class Duration(models.IntegerField):
description = "Stores the number of seconds as integer, displays as time"
def to_python(self, value):
# this method can receive the value right out of the db, or an instance
if isinstance(value, models.IntegerField):
# if an instance, return the instance
return value
else:
# otherwise, return our fancy time representation
# assuming we have a number of seconds in the db
return "x" + str(datetime.timedelta(0, value))
def get_db_prep_value(self, value):
# this method catches value right before sending to db
# split the string, skipping first character
hours, minutes, seconds = map(int, value[1:].split(':'))
delta = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
return delta.seconds
Это, однако, меняет представление значения поля в Python вообще, а не только в admin, что может быть нежелательным поведением. То есть, у вас есть object.duration == 'x00:1:12'
, который будет сохранен в базе данных как 72
.
См. Также документацию по настраиваемым полям .