How to cache Django Rest Framework API calls?

Ok, so, in order to use caching for your queryset: class ProductListAPIView(generics.ListAPIView): def get_queryset(self): return get_myobj() serializer_class = ProductSerializer You’d probably want to set a timeout on the cache set though (like 60 seconds): cache.set(cache_key, result, 60) If you want to cache the whole view: from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page class ProductListAPIView(generics.ListAPIView): …

Read more

Can to_representation() in Django Rest Framework access the normal fields

DRF’s ModelSerializer already has all the logic to handle that. In your case you shouldn’t even need to customize to_representation. If you need to customize it, I would recommend to first call super and then customize the output: class PersonListSerializer(serializers.ModelSerializer): class Meta: model = Person fields = (‘foo’, ‘bar’,) def to_representation(self, instance): data = super(PersonListSerializer, …

Read more

Django REST Framework image upload

you can create separate endpoint for uploading images, it would be like that: class ProductViewSet(BaseViewSet, viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer @detail_route(methods=[‘post’]) def upload_docs(request): try: file = request.data[‘file’] except KeyError: raise ParseError(‘Request has no resource file attached’) product = Product.objects.create(image=file, ….) you can go around that solution — update: this’s how to upload from …

Read more

Django REST Exceptions

The Django REST framework provides several built in exceptions, which are mostly subclasses of DRF’s APIException. You can raise exceptions in your view like you normally would in Python: from rest_framework.exceptions import APIException def my_view(request): raise APIException(“There was a problem!”) You could also create your own custom exception by inheriting from APIException and setting status_code …

Read more