序列化时区对象



我有一个模型,它有一个使用 django-timezone-field 的时区字段。它存储一个pytz对象在字段中。我想在响应中收到的是对象的区域instance.timezone_field.zone

使用该字段,我正在使用ReadOnlyModelViewSet,并且在发出GET请求时,我收到错误<DstTzInfo 'US/Arizona' LMT-1 day, 16:32:00 STD> is not JSON serializable

为什么我收到错误是有道理的,该对象不可 JSON 序列化。但是我将如何序列化它以使用区域子字段?

为了显示对象字段的结构,在shell中,我可以通过以下方式获取区域:

obj = MyModel.objects.get(id=1)
obj.timezone.zone
"US/Pacific"

我最终制作了一个自定义序列化程序字段,并在时区对象上使用区域字段。

class TimezoneField(Field):
    "Take the timezone object and make it JSON serializable"
    def to_representation(self, obj):
        return obj.zone
    def to_internal_value(self, data):
        return data
class AppSettingsSerializer(ModelSerializer):
    timezone = TimezoneField()
    class Meta:
        model = UserAppSettings

最新更新