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)
                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)
                        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())
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With