我认为你需要像这样(未测试的代码)::
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的代表,不仅在管理,这可能不是所期望行为。即,你有object.duration == 'x00:1:12'
,它将被保存到数据库为72
。请参阅documentation on custom fields。
我只是想改变字段的显示方式,而不是小部件。我也更新了这个问题。 – sorin 2011-06-09 10:39:48