'How to avoid code duplication in DRF views
class AddUsersView(UpdateAPIView): permission_classes = [IsAuthenticated]
def patch(self, request: Request, *args, **kwargs):
if ...
return successful_response({'data': "users added"})
else:
raise MeetingRoomDoesNotExist
class SubtractUsersView(UpdateAPIView): permission_classes = [IsAuthenticated]
def patch(self, request: Request, *args, **kwargs):
if ...
return successful_response({'data': "users subtracted"})
else:
raise MeetingRoomDoesNotExist
It seems my code is not DRY.What can I use to avoid code duplication.
Solution 1:[1]
DRF views are not different from other python classes. Your two best options here are basically to :
- Integrate the duplicated code in a function you'd call in both patch functions instead of rewriting it
- Override the
patch()function in a class and make your views inherit from it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ThomasGth |
