Dynamic Django queries (or why kwargs is your friend)
A very easy way to dynamically build queries in Django is to use Python kwargs (keyword arguments).
Let’s say we have a model that looks something like this:
class Entry( models.Model ):
user = models.ForeignKey( User, related_name = 'user_relation' )
category = models.ForeignKey( Category, related_name = 'category_relation' )
title = models.CharField( max_length = 64 )
entry_text = models.TextField()
deleted_datetime = models.DateTimeField()
Our goal is to dynamically build a query as we go in a view. Using kwargs, we can easily do something like this in our view code:
kwargs = {
# you can set common filter params here
}
# will return entries which don't have a deleted_datetime
if exclude_deleted:
kwargs[ 'deleted_datetime__isnull' ] = True
# will return entries in a specific category
if category is not None:
kwargs[ 'category' ] = category
# will return entries for current user
if current_user_only:
kwargs[ 'user' ] = request.user
# will return entries where titles match some search query
if title_search_query != '':
kwargs[ 'title__icontains' ] = title_search_query
# apply all filters and fetch entries that match all criteria
entries = Entry.objects.filter( **kwargs )
Its that simple. This approach seems quite pedestrian when you think about it. However, I didn’t find any examples online which actually shows this in use. It may be useful for someone new to Django.
UPDATE (Apr 30, 2009 @ 9:39AM) Based on the comments I received, I wanted to update this post a little bit. It was mentioned that this approach may not work if you use Q objects for complex lookups. It turns out that QuerySet filter() accepts both args and kwargs. So you could actually do something like:
kwargs = { 'deleted_datetime__isnull': True }
args = ( Q( title__icontains = 'Foo' ) | Q( title__icontains = 'Bar' ) )
entries = Entry.objects.filter( *args, **kwargs )
Very cool indeed. Django never ceases to amaze me.
-
Daniel Swarbrick
-
http://ayaz.wordpress.com/ ayaz
-
http://meiocodigo.com Vinicius Mendes
-
http://unhub.com/vacanti Vinicius Vacanti
-
http://philgo20.com PhilGo20
-
airstrike
-
Brooks Travis
-
Renato Pedigoni
-
Vladimir Dronnikov
-
http://www.michelepasin.org/techblog/ mike
-
http://www.ideatech.org Mansoorulhaq