我認爲你需要像這樣(未測試的代碼)::
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