How to change tastypie time format

2019-05-11 05:48发布

问题:

I'm writing an API server using Django 1.4.2 and Tastypie 0.9.11.

For all the datetime output, I'm using the default iso 8601 format, for example: "2012-11-20T02:48:19+00:00". But I want to get a "2012-11-20T02:48:19Z" format. How to do it easily without customizing each datetime field?

回答1:

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".



回答2:

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