2016-01-16 45 views
2

我有一個使用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序列化。但是,我如何序列化它以使用區域子字段?

表明目的場的結構,在殼我可以獲取區域:

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

回答

2

我最終作出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