Last modified: Oct 03, 2023 By Alexander Williams

Django Rest Framework ListCreateAPIView Example

Creating a Basic ListCreateAPIView


from rest_framework.generics import ListCreateAPIView
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelListCreateView(ListCreateAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Output:

# Output will vary based on your data and serializer

Customizing Queryset and Serializer


class CustomModelListCreateView(ListCreateAPIView):
    # Customize the queryset
    queryset = MyModel.objects.filter(active=True)
    
    # Use a custom serializer
    serializer_class = CustomMyModelSerializer

Output:

# Output will vary based on your data and serializer

Adding Permissions


from rest_framework.permissions import IsAuthenticated

class SecureModelListCreateView(ListCreateAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    
    # Add permissions to allow only authenticated users
    permission_classes = [IsAuthenticated]

Output:

# Output will vary based on your data and serializer

Customizing Response Format


class CustomResponseModelListCreateView(ListCreateAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    
    def list(self, request, *args, **kwargs):
        # Customize the response format
        response = super().list(request, *args, **kwargs)
        response.data = {
            'count': len(response.data),
            'results': response.data
        }
        return response

Output:

# Output will vary based on your data and serializer