修改Django Rest框架请求

时间:2018-01-22 08:21:26

标签: python django rest django-rest-framework httprequest

我设置了Django rest框架api,我正在尝试将当前时间插入到传入的PUT请求中。我目前有:

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.filter(done = False).order_by('-time')
    serializer_class = ItemSerializer
    paginate_by = None

    def list(self, request, *args, **kwargs):
        self.object_list = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(self.object_list, many=True)
        return Response({'results': serializer.data})

这会处理部分更新,但我希望能够发送一个设置Itemdone = True的请求,并让api也在发送到序列化程序的数据中插入一个unix时间戳。我可以像这样更改request对象,还是有更好的方法?

def put(self, request, *args, **kwargs):
    request.data['time'] = time.time()
    return self.partial_update(request, *args, **kwargs)

2 个答案:

答案 0 :(得分:1)

不是修改请求,而是覆盖序列化程序的方法update

Class ItemlSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemModel
        fields = '__all__'
        read_only_fields = ('time',)

    def update(self, instance, validated_data):
        instance.time = time.time()
        return super().update(instance, validated_data)

答案 1 :(得分:0)

使用序列化程序方法字段创建父序列化程序mixin。然后,所有序列化程序都可以继承此序列化程序mixin。

class TimeStampSerializerMixin(object):
    timestamp = serializers.SerializerMethodField()


    def get_timestamp((self, obj):
        return str(timezone.now())