Django Rest Retrieve API View with Slug

# views.py

from rest_framework.generics import RetrieveAPIView
from .models import YourModel
from .serializers import YourModelSerializer

class YourModelRetrieveAPIView(RetrieveAPIView):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer
    lookup_field = 'slug'

Explanation:

  1. Import RetrieveAPIView from rest_framework.generics, YourModel from .models, and YourModelSerializer from .serializers.

  2. Create a class named YourModelRetrieveAPIView that extends RetrieveAPIView.

  3. Set the queryset attribute to retrieve all instances of YourModel from the database using YourModel.objects.all().

  4. Define the serializer_class attribute as YourModelSerializer to serialize the retrieved model instances.

  5. Set the lookup_field attribute to 'slug'. This specifies that the view will use the 'slug' field from the YourModel as the lookup parameter to retrieve a single instance. ```

This code creates a Django REST framework API view that retrieves a single instance of a model using a slug field as a lookup parameter.