1 回答

TA貢獻1906條經(jīng)驗 獲得超10個贊
您可以為此創(chuàng)建一個自定義序列化程序字段:
import datetime
from django.utils import timezone
from rest_framework import serializers
from rest_framework.fields import Field
class TimeWithTimezoneField(Field):
default_error_messages = {
'invalid': 'Time has wrong format, expecting %H:%M:%S%z.',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def to_internal_value(self, value):
value_with_date = datetime.datetime.now().strftime('%Y-%m-%d') + ' ' + value
try:
parsed = datetime.datetime.strptime(value_with_date, '%Y-%m-%d %H:%M:%S%z')
except (ValueError, TypeError) as e:
pass
else:
return parsed
self.fail('invalid')
def to_representation(self, value):
if not value:
return None
if isinstance(value, str):
return value
return timezone.make_naive(value, timezone.utc).strftime("%H:%M:%S+00:00")
class ClinicSerializer(serializers.ModelSerializer):
start_at = TimeWithTimezoneField()
class Meta:
model = Clinic
fields = [
'id',
'name',
'start_at',
]
對于您的示例,start_at: 12:40:10+04:30將存儲為時區(qū)感知日期時間(UTC : 08:40:10+00:00)
添加回答
舉報