我有一个模型,它有一个使用 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"
最佳答案
我最终制作了一个 custom serializer field并在时区对象上使用时区字段。
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
关于django - 序列化时区对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822112/