[Django]-How to change tastypie time format

3👍

Formatting a date is probably best done in the templates. However, Tastypie allows you to add or modify fields returned by the API using the dehydrate cycle. For example:

# models.py
class MyModel(models.Model):
    iso8601_date = models.DateTimeField()

    class Meta:
        verbose_name = 'my_model'

# api.py
class MyResource(ModelResource):
    class Meta:
        queryset = MyModel.objects.all()

    def dehydrate(self, bundle):
        # Your original field: bundle.data['iso8601_date']

        # Newly formatted field.
        bundle.data['new_date_format'] = '2012-11-20T02:48:19Z'
        return bundle

Now, if you make the HTTP request, you should see a new line for “new_date_format”.

10👍

There is a configuration called TASTYPIE_DATETIME_FORMATTING in this page http://django-tastypie.readthedocs.org/en/latest/serialization.html. However, this gives you limited options(iso-8601 & rfc-2822).

What you could do is use a custom Serializer for your resource like

# models.py
class MyModel(models.Model):
    class Meta:
        verbose_name = 'my_model'

# api.py
from custom_serializer import MySerializer
class MyResource(ModelResource):
    class Meta:
        queryset = MyModel.objects.all()
        serializer = MySerializer()

#custom_serializer.py
from tastypie.serializers import Serializer
class MySerializer(Serializer):
    def format_datetime(self, data):
        return data.strftime("%Y-%m-%dT%H:%M:%SZ")

This has been detailed here – http://django-tastypie.readthedocs.org/en/latest/serialization.html

Leave a comment