[Django_Rest_Framework] Views and Viewsets attributes

Rex Chiang
1 min readOct 31, 2021
  • Start from APIView and GenericAPIView, there have several attributes that we could control basic view and viewset behavior.
  • Since GenericViewSet inherit from GenericAPIView, and ModelViewSet inherit from GenericViewSet, they could use these attributes.
from DRFapp.models import User
from DRFapp.serializers import UserSerial

class UserUpdateViewset(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerial

http_method_names = ["get", "put", "delete"]
lookup_field = "name"
pagination_class = None

queryset

  1. Use for returning objects from the view, or you could override the get_queryset method.
  2. Override get_queryset method instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

serializer_class

  1. Use for validating and deserializing input, and for serializing output.
  2. We could override the get_serializer_class method to customize serializing and deserializing.

http_method_names

  1. Define the HTTP methods to block some methods that we don’t want users to use.

lookup_field

  1. Use the field in our model to replace the default value ”pk” .
  2. Now we can use our model field to lookup individual model instances.

pagination_class

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
  1. Use to paginate list results.
  2. Default to use the setting in settings.py, or you could customize in each view.

--

--