Login

Snippets by zerok

Snippet List

Manager method for limiting GenericForeignKey queries

This is a simple manager that offers one additional method called `relate`, which fetches generic foreign keys (as referenced by `content_type` and `object_id` fields) without requiring one additional query for each contained element. Basically, when working with generic foreign keys (and esp. in the usecase of having something like a tumblelog where you use an additional model just to have a single sorting point of multiple other models), don't do something like `result = StreamItem.objects.select_related()` but just fetch the content type with `result = StreamItem.objects.select_related('content_type')`, otherwise you will end up with first one query for the list of StreamItems but then also with one additional query for each item contained in this resultset. When you now combine the latter call with `result = StreamItem.gfkmanager.relate(result)`, you will just get the one query for the item list + one query for each content type contained in this list (if the models have already been cached). For further details, please read [this post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) on my blog.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

I18n URLs via Middleware

This is an example middleware that is highly inspired by how Symfony handles [i18n in URLs](http://www.symfony-project.com/book/trunk/13-I18n-and-L10n#Changing the Culture for a User). You basically set a (?P<dj_culture>[\w-]+) pattern in your URL and this middleware will determine the language to use for the i18n toolkit for Django. It also removes the dj_culture parameter after dealing with it, so that you don't have to change all the views you want this middleware to work with.

  • middleware
  • i18n
  • url
Read More

zerok has posted 2 snippets.