I wanted lookups on tags to be case insensitive by default, so that things like
Tag.objects.get(name='Tag')
would return any similar tags (ignoring case differences), i.e. `<Tag: tag>`.
This snippet makes lookup on the 'name' field case-insensitive by default, although
case-sensitive lookups can still be achieved with 'name__exact'. Methods like get_or_create
will work as expected and be case-insensitive.
Ever want to call stored procedures from Django easily? How about PostgreSQL functions? That's that this manager attempts to help you with. To use, just stick this in some module and in a model do:
class Article(models.Model):
objects = ProcedureManager()
Now you can call procedures (MySQL or PostgreSQL only) to filter for models like:
Article.objects.filter_by_procedure('ProcName', request.user)
This will attempt to construct a queryset of objects. To just get random values, do:
Article.objects.values_from_procedure('ProcName', request.user)
Which will give you a list of dictionaries.
I know you're thinking, *what the heck could that title mean?*
I often find myself wanting to filter and order by the result of a COUNT(*) of a query using a method similar to the [entry_count example](http://www.djangoproject.com/documentation/db-api/#extra-select-none-where-none-params-none-tables-none). Writing this many times is tedious and hardcoding the table and column names made me cringe, I also wanted the counts to result from more complex queries.
This is a method you can add to your custom Manager to do this easily. It's not an ideal syntax, but it's good for the amount of code required.
Example: suppose we have some articles we want to filter and order by comments and visit logs to show the most popular...
class ArticleManager(models.Manager):
count_related = _count_related
class Article(models.Model):
pub_date = models.DateTimeField(auto_now_add=True)
objects = ArticleManager()
class Comment(models.Model):
article = models.ForeignKey(Article)
is_spam = models.BooleanField(default=False)
class Visit(models.Model):
article = models.ForeignKey(Article)
referrer = models.URLField(verify_exists=False)
search_query = models.CharField(maxlength=200)
Notice how the ArticleManager is given the `count_related` method. Now you can find the most popular like so...
Order by non-spam comments:
Article.objects.count_related(Comment.objects.filter(
is_spam=False)).order_by('-comment__count')
Order by incoming non-search-engine links:
Article.objects.count_related(Visit.objects.filter(
referrer__isnull=False, search_query__isnull=True),
'links').order_by('-links')
Order by total visits:
Article.objects.count_related(Visit).order_by('-visit__count')
Note: Doesn't work if `query` contains joins or for many-to-many relationships, but those could be made to work identically if there's demand.