In a Django tutorial I am watching someone writes:
class GetUserProfileView(APIView):
def get(self, request, format=None):
# user profile get code
class UpdateProfileView(APIView):
def put(self, request, format=None):
# user profile put code
whereas to me a beginner it seems to make way more sense to organize it in one view:
class ProfileView(APIView):
def get(self, request, format=None):
# user profile get code
def put(self, request, format=None):
# user profile put code
Is there a reason for organizing them into different views or is the tutorial maker unexperienced?
Usually such views are indeed grouped, that concept is called a ViewSet
[drf-doc], which can group a list
(usually a GET request without any "key" for an object), retrieve
(usually a GET request with a key for which we retrieve an item), create
(usually a POST request), update
(usually a PUT request), partial_update
(usually a PATCH request), and destroy
(usually a DELETE request).
Typically one only uses an APIView
in case it is not a "default" scenario like retrieving the objects, serializing these, and returning these. So only if you do something more sophisticated. One often uses different APIView
s for example if the serializer or other logic is different depending on the scenario, in that case often the logic will disambiguate betwen the scenarios often making it less elegant than splitting it in different classes.