BenW
unread,Aug 10, 2009, 9:45:54 AM8/10/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Sign in to report message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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