Custom model field and Django-admin -- error

49 views
Skip to first unread message

BenW

unread,
Aug 10, 2009, 9:45:54 AM8/10/09
to Django users
Hello,

I'm working with a legacy database that stores datetimes as unsigned
ints. Rather than do the conversion with properties on the model I've
written a custom Field 'UnixDateTimeField':

class UnixDateTimeField(models.DateTimeField):

__metaclass__ = models.SubfieldBase

def get_internal_type(self):
return 'PositiveIntegerField'

def to_python(self, value):
if value is None or isinstance(value, datetime):
return value
if isinstance(value, date):
return datetime(value.year, value.month, value.day)
return datetime.fromtimestamp( float(value) )

def get_db_prep_value(self, value):
return int( time.mktime( value.timetuple() ) )

def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.to_python(value).strftime('%Y-%m-%d %H:%M:%S')

class MyModel(models.Model):
time = UnixDateTimeField()

# This Works:
>> MyModel.objects.filter(time__lte=datetime.now())
[<MyModel>, <MyModel>, etc..]
>>

# This works:
>> MyModel.objects.all()[0].time
datetime.datetime(2009, 8, 10, 6, 40, 7)
>>

# Doesn't work:
>> MyModel.objects.all().values('time')
[{'time': 1249911607L}, {'time': 1249911607L}, {'time':
1249911607L}, ...]
>>

The same thing happens in the Admin when I specify date_hierarchy in
my ModelAdmin a one of these fields. Why are the standard accessor
methods (namely 'to_python()') not being called here? How can I make
the custom Field more robust?

Thank you,

Ben

Alex Gaynor

unread,
Aug 10, 2009, 11:04:03 AM8/10/09
to django...@googlegroups.com
This looks like ticket #9619: http://code.djangoproject.com/ticket/9619

Alex

--
"I disapprove of what you say, but I will defend to the death your
right to say it." -- Voltaire
"The people's good is the highest law." -- Cicero
"Code can always be simpler than you think, but never as simple as you
want" -- Me

Jean Stebens

unread,
Aug 10, 2009, 11:13:34 AM8/10/09
to django...@googlegroups.com
Beside that - I would like to see the UnixDateTimeField in django by
default - it's not uncommon to use unix timestamps for applications
which do support quite alot of databases, especially when mssql is one
of them.

Cheers,
Jean

BenW

unread,
Aug 10, 2009, 11:21:52 AM8/10/09
to Django users
Excellent that it was reported, but bad that it's not considered a
'bug' -- Any suggestions on how to use date_hierarchy (and probably
others) with my field?

On Aug 10, 8:04 am, Alex Gaynor <alex.gay...@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages