Search code examples
djangotastypie

Alter a value passed by a filter in request to Tastypie


I want to allow the consumers of my API to filter on a datetimefield with auto_now=True. The caveat is that I want them to be able to do so with a UNIX format (ie : 1380783641 instead of 2013-10-02T16:46:24.030321 which is the default format.)

I've already dehydrated the field in order to render it as such with :

    def dehydrate_created_on(self, bundle):

        return bundle.data['created_on'].strftime('%s')

How can I do the same for the value passed in a request to be filtered on ?

/api/v1/model/?created_on__gt=1380783641

This returns a ValueError : (in French)

"error": [
"Le format de la valeur « 1380783641 » n'est pas valide. Le format correct est AAAA-MM-DD HH:MM[:ss[.uuuuuu]][FH]."
]

Thanks for your help.


Solution

  • A hacky workaround based on what can be found here is to redefine the build_filter method:

    def build_filters(self, filters=None):
        if filters is None:
            filters = {}
        orm_filters = super(YourResource, self).build_filters(filters)
        for filt in orm_filters:
            if filt.startswith('created_on'):
                orm_filters[filt] = datetime.datetime.fromtimestamp(float(filters[filt]))
        return orm_filters