Consider this Django REST Framework generic view:
from rest_framework import generics
from myapp.models import Book
from myapp.serializers import BookSerializer
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
What HTTP methods does this view support by default?
Think about what ListCreateAPIView is designed for.
ListCreateAPIView supports listing objects with GET and creating new objects with POST.
You want to filter the queryset based on the current user in a generic view. Which code snippet is correct?
from rest_framework import generics from myapp.models import Article from myapp.serializers import ArticleSerializer class UserArticles(generics.ListAPIView): serializer_class = ArticleSerializer def get_queryset(self): # Your code here pass
Remember how to access the request object inside a view method.
Inside a view method, the request is accessed via self.request. So filtering by author=self.request.user is correct.
Using Django REST Framework's CreateAPIView, what is the typical HTTP status code returned after successfully creating an object?
Think about the standard HTTP status code for resource creation.
DRF's CreateAPIView returns 201 Created on successful creation, indicating a new resource was made.
Given this view code:
from rest_framework import generics
from myapp.models import Product
from myapp.serializers import ProductSerializer
class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = ProductSerializer
def get_object(self):
return Product.objects.get(pk=self.kwargs['id'])
When accessing this view, it raises KeyError: 'id'. Why?
Check how URL parameters are passed to the view.
The view expects 'id' in self.kwargs, but if the URL pattern does not include 'id' as a named parameter, self.kwargs['id'] does not exist, causing the error.
You want to create an API endpoint that allows users to only read data (no create, update, or delete). It should support listing all objects and retrieving a single object by ID. Which DRF generic view class is the best choice?
Think about a class that supports both list and detail read-only actions in one place.
ReadOnlyModelViewSet provides both list and retrieve actions but disables create, update, and delete, making it ideal for read-only endpoints.