Sobes.tech
Junior — Middle

How can the data display format be changed in ModelViewSet for specific requirements?

sobes.tech AI

Answer from AI

In Django REST Framework, to change the data display format in a ModelViewSet according to specific requirements, different serializers are usually used. This can be done by overriding the get_serializer_class method in your ModelViewSet.

Example:

from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer, ProductDetailSerializer

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return ProductSerializer  # Short format for list
        if self.action == 'retrieve':
            return ProductDetailSerializer  # Detailed format for a single object
        return ProductSerializer

Thus, different serializers with the required data format can be used for different actions (list, retrieve, create, etc.). You can also change the format depending on request parameters or user permissions by checking them in get_serializer_class.