The Power and the Glory of Django
I have been doing a lot of work with (and a little bit ON) the Django web framework lately. Just now, I learned something that blew my mind.
Django has an ORM layer that uses Python's powerful metaprogramming capabilities to automagically wire up classes that present a functional interface to a database table. Ergo, to get a list of Foozle objects stored in the database, you do:
foozles.get_list()
If you want to restrict which foozles you get, you pass in keyword arguments that get dissected by the framework into a fieldname and an operator. E.g., to get all the foozles that are bigger than 5 (whatever foozle size is measured in):
foozles.get_list(size__gt=5)
Well, I am building a search feature, and part of that is preprocessing the search words to recognize keywords and the like. For example, if a keyword gets recognized as the name of a user, I want to pull out that user's id and add it to the list of field lookups.
I thought this was going to be really damned hard. Then I thought to try something like this:
kw = {'id__exact': 39}
auth_users.get_list(**kw}
Naturally, since I figured it would be difficult, IT JUST WORKED. Needless to say, I was flabbergasted, and this is going to make building a smart search engine a snap.
This works because of one of two possible things:
1. I was not fully conversant with behavior of Python keyword arguments. This might work because, under the hood, Python treats all keyword arguments as a dictionary with string keys.
2. Someone working on Django anticipated this use case and baked it in.
Either way, wow!