HackSoftware / Django-Styleguide

Django styleguide used in HackSoft projects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use ViewSet instead of APIView

HomaDev opened this issue · comments

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!

@HomaDev hello and thanks for asking 👋

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 🙌

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

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