HackSoftware / Django-Styleguide

Django styleguide used in HackSoft projects
MIT License
5k stars 511 forks source link

Use ViewSet instead of APIView #143

Closed HomaDev closed 8 months ago

HomaDev commented 8 months ago

Hi, I wanted to ask the reason behind the "one view - one endpoint" approach? Why not use ViewSet (in its base form) to create one ViewSet for the model, and when needed use ad-hoc methods? For me, it sounds super easy, flexible, and clean.

Also thanks for the great guidelines!

RadoRado commented 8 months ago

@HomaDev hello and thanks for asking :wave:

There are a couple of things and I'll start with the simplest answer:

It's way more simple. One API per action is easier to reason about, than an entire ViewSet, that may be doing things that you don't want to be happening, but they are happening nevertheless, because of the abstraction.

And if you want to patch something from the ViewSet, you introduce additional levels of indirection (jumping thru implementation, just to find where to plug in)

Now, following on that, our Django Styleguide revolves around the idea of the "service layer", meaning, separating your application domain (also called business logic), from your application framework (Django, Django Rest Framework, etc.)

It's much more cleaner to call the service layer from a simple APIView, than it is from ViewSet.

The ViewSet mixes both framework & domain logic & we want to avoid that.

Now, having said all of this, use whatever makes sense for you & be consistent with it.

And, of course, if you have more questions - feel free to ask them here :raised_hands:

HomaDev commented 8 months ago

Ok, it makes sense, thanks for the answer.

I wouldn't say that there are many new abstractions on it, but if you need to connect something custom to it, ViewSet causes some problems.

The issue could be closed I guess

RadoRado commented 8 months ago

@HomaDev closing it. Feel free to reopen if you have other questions :raised_hands: