Hi
I've tried to create a custom Field for the database to store  
Timedelta objects. Since I only need exactness to the minute and won't  
have any large timedeltas I'm using a simple Integer to store it in  
the database. Maybe I'll make this configurable later.

this is the code:
============
from django.db.models.fields import IntegerField, Field
from django.core import validators
import datetime
from contrib.numeric_utilities import timedelta2minutes

class TimedeltaField(IntegerField):
    def to_python(self, value):
        # turns the integer saved in the database to a python  
timedelta object
        if value is None:
            return value
        if isinstance(value, datetime.timedelta):
            return value
        validators.isInteger(str(value), None)
        try:
            return datetime.timedelta(minutes=int(value))
        except (TypeError, ValueError):
            raise validators.ValidationError, u"This value must be an  
integer (it gets converted to a Timedelta)"
    def get_db_prep_save(self, value):
        # Turns the input into a integer of minutes for save in db
        if isinstance(value, datetime.timedelta):
            value = timedelta2minutes(int(value))
        return Field.get_db_prep_save(self, value)
    def get_internal_type(self):
        return "IntegerField"
=========
timedelta2minutes is a simple function that returns an integer.


On the commandline:
=================
 >>> from mytest.models import *;
 >>> t = MyTest.objects.all()[0]
 >>> t.a_timedelta
2342
 >>> type(t.a_timedelta)
<type 'int'>
 >>> t.validate()
{}
 >>> t.a_timedelta
datetime.timedelta(0, 39960)
 >>> type(t.a_timedelta)
<type 'datetime.timedelta'>
==========

So... until I run validate() at least once the field returns the int  
from the database instead of the converted value from to_python(). I  
ran some tests with print statements in the to_python methods... they  
never get called until validate() is run. The same for the built-in  
DateField, but there the value still gets magically returned as a  
datetime.date object.

Saving works fine... I can assign a timedelta objects to a_timedelta  
and save() and the value gets correctly saved to the database as a int.

What am I doing wrong, that the value is only present as a datetime  
object once I've done a validate()?




--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to