4

I have a Django rest framework api set up, and I'm trying to insert the current time into incoming PUT requests. I currently have:

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})

This handles partial updates, but I would like to be able to send a request setting an Item to done = True and have the api also insert a unix timestamp into the data sent to the serializer. Could I alter the request object like this, or is there a better way?

def put(self, request, *args, **kwargs):
    request.data['time'] = time.time()
    return self.partial_update(request, *args, **kwargs)
1
  • What do your model and serializer look like? Commented Jan 22, 2018 at 8:28

2 Answers 2

4

Instead of modifying request, override serializer's method 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)
Sign up to request clarification or add additional context in comments.

Comments

1

You make a Parent serializer mixin with a serializer method field. Then all your serializers can inherit this serializer mixin.

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


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.