3 ms·
The most important caveat that the author mentions: this advice may not apply to Django Rest Framework. Class based views for DRF are awesome because they repr
by sergioisidoro 3y ago
The most important caveat that the author mentions: this advice may not apply to Django Rest Framework.
Class based views for DRF are awesome because they represent a resource. It has been a great experience writing REST APIs with class based views, and it reduces boilerplate with a tolerable amount of implicit logic.
But as soon as I need to render a simple html page from a request, I share the frustration of the author.
- pdhborges 3y agoI read the article and I'm left scratching my head why this advice doesn't apply to DRF. The DRF Generic ViewSets and Views provide maximum magic plus they also shift part of the creation process into Model Serializers. Doing anything custom with this setup involves overriding bunch of methods and chasing their original definitions through an handfull of mixins.
- rpep 3y agoCBV doesn't require you to do anything in particular other than implement retrieve/list/etc. methods on the GenericViewSet as needed, and get/post/etc. on GenericAPIView. You can use the convenience methods in Django and mixins, but as soon as you get beyond a simple case, they start to become a hindrance. The only thing beyond that that I'd recommend is specifying a get_serializer_class method since it simplifies your boilerplate and plays well with drf-spectacular for generating your API documentation. I generally don't use ModelSerializer unless the logic is very simple, I've been meaning to write a blog post for a long while about avoiding it when your data model is split across two database tables.
- pdhborges 3y agoIn my current codebase there is a lot more overriding going on than simply implementing the retrieve/list/etc... methods. On a quick review I found overrides for: - get_object - get_serializer_class - perform_create - get_queryset - get_serializer_context - perform_destroy
- rpep 3y agoIt depends on how much you want to rely on Mixins and using Serializer classes to do more than just serialise JSON. Neither of those are compulsory to use, and the more you lean into them the more inheritance you’re forced to do as soon as you need to customise the behaviour.