如何改变tastypie时间格式 [英] How to change tastypie time format

查看:121
本文介绍了如何改变tastypie时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.4.2和Tastypie 0.9.11编写一个API服务器。



对于所有的datetime输出,我使用的是默认的iso 8601格式,例如:2012-11-20T02:48:19 + 00:00。但是我想得到一个2012-11-20T02:48:19Z的格式。如果没有自定义每个日期时间字段,这样做很容易?

解决方案

格式化日期可能最好在模板中完成。但是,Tastypie允许您使用。例如:

 #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):
#您的原始字段:bundle.data ['iso8601_date']

#新格式的字段。
bundle.data ['new_date_format'] ='2012-11-20T02:48:19Z'
返回包

现在,如果您提出HTTP请求,您应该看到new_date_format的新行。


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?

解决方案

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

这篇关于如何改变tastypie时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆