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:
Import
RetrieveAPIView
fromrest_framework.generics
,YourModel
from.models
, andYourModelSerializer
from.serializers
.Create a class named
YourModelRetrieveAPIView
that extendsRetrieveAPIView
.Set the
queryset
attribute to retrieve all instances ofYourModel
from the database usingYourModel.objects.all()
.Define the
serializer_class
attribute asYourModelSerializer
to serialize the retrieved model instances.Set the
lookup_field
attribute to 'slug'. This specifies that the view will use the 'slug' field from theYourModel
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.