Django-rest-framework timezone aware renderers/parsers

后端 未结 3 1641
情书的邮戳
情书的邮戳 2020-12-25 14:49

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

3条回答
  •  心在旅途
    2020-12-25 15:01

    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)
    

    and now you can use it in ModelSerializer:

    class XSerializer(serializers.ModelSerializer):
        start = DateTimeTzAwareField()
        end = DateTimeTzAwareField()
    
        class Meta:
            model = XModel
            fields = (
                 'id',
                 'start',
                 'end',
            )
    

提交回复
热议问题