[Django_Rest_Framework] Views and Viewsets attributes
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
- Use for returning objects from the view, or you could override the get_queryset method.
- 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
- Use for validating and deserializing input, and for serializing output.
- We could override the get_serializer_class method to customize serializing and deserializing.
http_method_names
- Define the HTTP methods to block some methods that we don’t want users to use.
lookup_field
- Use the field in our model to replace the default value ”pk” .
- 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,
}
- Use to paginate list results.
- Default to use the setting in settings.py, or you could customize in each view.