Django-rest-framework时区识别渲染器/解析器 [英] Django-rest-framework timezone aware renderers/parsers

查看:857
本文介绍了Django-rest-framework时区识别渲染器/解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个可以为位于世界不同地方的人提供的应用程序。

我正在使用Django-Rest-Framwork来进行客户端和服务器之间的通信。

所有的DateTime值都以UTC的形式保存到数据库(我有 USE_TZ = True TIME_ZONE ='格林威治' in settings.py)。

I'm building an app that would serve people located in different places arround the world.
I'm using Django-Rest-Framwork for the communication between the clients and the server.
All DateTime values are saved to the DB as UTC (I have USE_TZ = True and TIME_ZONE = 'Greenwich' in settings.py).

我将从用户那里获取他/她的本地时区。

I will be getting from the user his/her local timezone.

测试 DRF时区意识我用固定时区写了这个中间件:

To test DRF for timezone awareness I wrote this middleware with fixed timezone:

import pytz
from django.utils import timezone

class TimezoneMiddleware(object):
    def process_request(self, request):
        timezone.activate(pytz.timezone("Asia/Jerusalem"))

问题是:

我有一个case来自用户的start_time和end_time字段在用户的 LOCAL 时区中包含数据时间将$ code> UnicodeJSONRenderer 转换为 ModelSerializer ,然后保存到DB。但是,它们保存为,就好像它们在UTC

The problem is:
I have a case in which I'm getting from the user "start_time" and "end_time" fields containting datetimes in the user's LOCAL timezone which gets through the UnicodeJSONRenderer to a ModelSerializer and then saved to the DB. However, they are saved as if they were in UTC.

在这一点上,我期望串行器(或解析器)处理日期时间我从执行 timezone.activate(pytz.timezone(亚洲/耶路撒冷))之后,从用户输入的日期时间需要从亚洲/耶路撒冷转换为UTC,然后保存到数据库。 code>。

At this point I would expect the serializer (or parser) to treat the datetime input from the user as datetime that needs to be converted from "Asia/Jerusalem" to UTC before saving to the DB since I performed timezone.activate(pytz.timezone("Asia/Jerusalem")).

当通过 JSONParser 在响应中解析数据时也是如此。 br>
当期望返回的JSON中的DateTime字段处于中间件激活的时区时,它们将返回为UTC。

The same goes when the data is parsed back in the response through JSONParser.
While expecting DateTime fields in the returned JSON to be in the timezone activated in the middleware, they are returned as UTC.

如何轻松实现在DRF中?

How can I easily achieve that in DRF?

推荐答案

我有同样的问题,并通过添加新的字段类型解决了:

I had the same problem and solved it by adding new type of field:

class DateTimeTzAwareField(serializers.DateTimeField):

    def to_native(self, value):
        value = timezone.localtime(value)
        return super(DateTimeTzAwareField, self).to_native(value)

现在可以在 ModelSerializer

and now you can use it in ModelSerializer:

class XSerializer(serializers.ModelSerializer):
    start = DateTimeTzAwareField()
    end = DateTimeTzAwareField()

    class Meta:
        model = XModel
        fields = (
             'id',
             'start',
             'end',
        )

这篇关于Django-rest-framework时区识别渲染器/解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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