Hello. In my projects, I am struggling to decide whether to use function or class based views for things like CRUD functionality. Are there any advantages of class based views over function based and vice versa?
In what situations are function based views better and when are class based views better?
Also does it ultimately come down to personal preference how you write your views, or are there advantages of one over the other, and situations where one is better than the other. If so what are these? Thanks.
<opinion mode on>
In one sense, the function-based views are easier to understand when you’re first getting started, especially if you’re not all that comfortable with Python classes, class inheritance, and the concepts behind the Method Resolution Order (MRO).
There’s less to learn and understand with the function-based views - which means there’s more functionality that you’ll have to code yourself.
On the other hand, once you’ve gotten a good grounding on all the above topics, the generic Class Based Views can save you a lot of work. They provide a great framework for building applications with a minimum of work.
Now, there are some people who say that the Django-provided generic CBVs are too complicated and that it can be difficult to understand where and how to extend them for your own needs - and I’m not entirely unsympathetic with that position.
As a result of that, there are 2 third-party resources worth exploring.
-
The Classy Class Based View documentation site is a fantastic resource for browsing through the class structure to understand what models and attributes are involved in the views and understanding how all the pieces are put together.
-
Django Vanilla Views is a third-party package that provides the same functionality as the built-in views, but are a lot simpler to understand and extend. (Disclaimer: I’ve never personally used them beyond some brief experimentation, but a couple people that I have a lot of respect for recommend them highly. And so since I trust their opinions…)
But really, it is a matter of taste. Functionally, there is no difference - they both have the same effect. They take a request and emit a response.
Where I find there to be a most significant difference is that the CBVs make it easier to apply functionality across a number of different views. For example, we have a custom security layer that applies to most of our views. Rather than adding that code to every view, we’ve created it as a mixin so that it’s automatically used in every view for which it applies.
<opinion mode off>
1 Like
Great. Thank you, this helps a lot.