'generics vs viewset in django rest framework, how to prefer which one to use?

How to prefer which one of generics and viewset to use? in other words when should I use generics and when should I use viewset for building api. I know that they do the same thing, but viewset has routers, so in what situation generics are better than viewset?



Solution 1:[1]

My golden rule for this is to use generics whenever I have to override the default methods to accomplish different specifications from list and details views.

For instance, when you have different serializer classes for listing your resources and for retrieving a resource details by id I consider that using generics is a better option since probably these two endpoints' logic is going to evolve separately. Keep in mind is a good practice to maintain different logics decoupled.

When your endpoint is very simple and you don't need to customize logic between list/create and retrieve/update/delete operations you can use viewset, but yet having in mind it may be good to separate it in two views in case these operations' logic start growing in different paths.

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 hugobessa