3 ms·
This is a great guide. Some thoughts having been working with Django for a while: FBV are superior in most cases. Less magic, just code. CBV are better when y
by IgorPartola 3y ago
This is a great guide. Some thoughts having been working with Django for a while:
FBV are superior in most cases. Less magic, just code.
CBV are better when you have complex operations. Not everything is just CRUD, and sometimes you do need a long POST method and a long GET. Sometimes the two share a bunch of functionality that makes sense to break out into its own function(s) but that functionality clearly belongs in the view layer.
Recently I worked on a system where my models all shared a fairly complex system of being versioned and having start_on and ends_on dates to make them temporal. In fact each concept had two models: a root that most other models refer to and a version. While the dozen models were all different the logic of processing creating and updating these models instances was the same between all of them but each model had its own unique additional rules for how to process them. So I created a pair of base CBV (one for a listing and one for a single object) that implemented CRUD methods for them and then each object got its own CBV pair based on those. I tried this with FBV and it was much messier, especially with form validation shared between POST and PUT. Sometimes a complicated setup like this requires CBV to create neat and concise code (relatively speaking).
On moving logic to the model layer: my litmus test for this is whether the logic is used more than once. I’d you have a view that fetches model instances based on a complex filter (dates, user permissions, etc.), but it literally is the only one of its kind, why spread logic out though model code? But if you have either multiple views that do this, or more likely views that share logic with management commands and/or background tasks then it absolutely makes sense.
Service layers leak abstractions. Django doesn’t support this as a first class citizen, so why should you? You won’t be able to switch to a different framework just by rewriting what your service layer talks to so just don’t do it.
DRF is a CPU hog even at mild loads. I use a home grown model-to-JSON serializer that is quite a bit faster and Django forms to validate input.