django如何将字段序列化为DateTimeRangeField

时间:2018-06-22 08:59:17

标签: python django serialization django-models django-rest-framework

将字段序列化为DateTimeRangeField时遇到麻烦。该请求当前必须具有以下格式:

data = {"time":
         {
           "lower": timeThing,
           "upper": laterTimeThing
         }
       }

我希望它在请求中看起来像这样:

data = {
           "start": timeThing,
           "end": laterTimeThing
       }

这样我就可以将开始/结束序列化为较低/较高。 这是我的模型:

class Example(models.Model):
    time = DateTimeRangeField()
    user = models.ForeignKey('user.User')

class ExampleAPI(ListCreateAPIView):
    serializer_class = ExampleSerializer
    pagination_class = None
    queryset = Example.objects.all()

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class ExampleSerializer(serializers.ModelSerializer):
    time = DateTimeRangeField(write_only=True)
    user = serializers.ReadOnlyField(source='user.id')

    class Meta:
        model = Example
        exclude = ['user']

我尝试创建一个custom field,但是它似乎并没有覆盖到to_representation或to_internal_value中。我收到的错误消息是{'time':['此字段为必填。']}

1 个答案:

答案 0 :(得分:0)

您可以尝试

import datetime

from rest_framework import serializers
from drf_extra_fields.fields import DateRangeField


class RangeSerializer(serializers.Serializer):
    ranges = DateRangeField()


serializer = RangeSerializer(data={'ranges': {'lower': datetime.date(2015, 1, 1), 'upper': datetime.date(2015, 2, 1)}})