Django-Styleguide
Django-Styleguide copied to clipboard
Convince me about selectors?
Thanks for this guide - it's been massively helpful for my personal projects. I used to follow the old fat models approach of shoving everything into models, and my personal experience has been transitioning to services has made my code 10x better.
The only part I haven't migrated yet are the pull operations. In my app, I've been mainly creating a CustomQuerySet for each model. Then I can simply use objects = CustomQuerySet.as_manager() in my model definition. I have not transitioned over to selectors (e.g. user_list) yet. CustomQuerySet has been helpful since I can chain my lookups and serves as a way to group complex pull logic.
I guess I'm curious:
- Do you typically use selectors for every one of your django projects?
- Do you use any CustomQuerySet's or is all pull logic completely contained within the selectors?
- How do I think about why selectors are better? In what cases is it preferred to just using a CustomQuerySet, which already can group complex pull logic?
@eddielu Hello :wave:
To be fair, selectors are a "weaker" concept, compared to the rest of what this styleguide has to offer.
From our experience so far, when we have a more complex way of fetching and building the data together, we need the flexibility of "I have a function and I'll do whatever's necessary here". This is how the idea for selectors was born.
Now, I say that this is a weaker concept, because whenever things get complicated in the "read" path, we tend to offload the computation some place else, and maintain either a cache or a computed table (materialized view) and simply return data from an API.
And when that happens, the code that does the computation - how you call it - selector or a service - doesn't matter that much.
Of course, custom query sets play a big role and if this is how you approach things - you should consider doing this.
And, of course, the other time we have a good use case for selectors, is when we have checks to be made, that go beyond the standard permissions of what Django and/or Django Rest Framework has to offer.
Hope that clarifies things a bit.
Cheers!
Closing this for now.
Feel free to reopen if needed.
Cheers!