AttributeError:序列化程序DateField将值转换为字节

时间:2019-05-13 14:54:50

标签: django-rest-framework

我有以下序列化器:

1. Remove identified database from Availability Group.
2. Restore that database.
3. Add database to Availability Group post restore operation.

这是我的观点:

class MySerializer(Serializer):
    my_date = DateField(read_only=True)

    class Meta:
         fields = [
             'my_date',
         ]

我在视图的最后一行收到以下错误:

  

AttributeError:“字节”对象没有属性“ isoformat”

调试代码时,我发现class InvoiceViewSet(GenericViewSet): """ A generic ViewSet for viewing and editing the inquiries. This view gets the union of Invoices and Credit Notes """ serializer_class = MySerializer filterset_class = MyFilter pagination_class = StandardResultsSetPagination def list(self, request, *args, **kwargs): object_list = self.get_queryset() filter_queryset = self.filter_queryset(object_list) # Apply filters paginated_queryset = self.paginate_queryset(filter_queryset) # Apply pagination serializer = self.get_serializer(paginated_queryset, many=True) return self.get_paginated_response(serializer.data) 字段在某个时候转换为类型my_date,不再是日期。

当对象加载到序列化程序中时,显然会发生这种情况。当我用django ORM查询对象时,字段的类型正确。

有什么想法为什么会发生以及如何解决?

Stacktrace,根据要求:

byte

最佳

罗恩

PS:我正在使用DRF v3.9.3

1 个答案:

答案 0 :(得分:1)

似乎只是DRF中的一个错误...在将对象加载到序列化程序中时,serializers.DateField的值被强制转换为byte

这是我的快速解决方案:

from rest_framework.fields import DateField


class CustomDateField(DateField):

    def to_representation(self, value):
        # It seems that DRF has a bug and casts values of serializers.DateField() to byte instead of something useful.
        if isinstance(value, bytes):
            value = value.decode("utf-8")
        return super().to_representation(value)