Named Scopes for Django
Monday, June 22nd, 2009There are really only a handful of features I miss about Ruby on Rails, having switched over to using only Django about a year ago. One of the biggest among these has been named scopes.
What a named scope does in Rails, in Django terms, is allow you to name a given query and use it as a base, or “scope,” for further queries. In other words, your narrowing down the results upon which additional queries that you run will be executed.
It’s pretty much the same idea behind modifying initial Manager QuerySets as outlined in the Django documentation, with one major difference: Scopes can be chained. Chaining is the feature I had long coveted, and I had been banging my head around for a solution for the last few months.
The other day while I was poking around the internals a bit though, a decent idea came to me. I realized it would be quite simple for me to extend the default Manager class with an attribute where I could store QuerySet methods I wanted to execute as part of a scope, and then overwrite get_query_set() with a hook that ran these methods before executing the rest of the query.
This turned out to be a nice strategy, and with the addition of some decorators the interface itself turned out to be extraordinarily simple.
