-
Keyword search with Python and SQLobject
-
After a discussion with my friend Themis, I decided of reminding myself how great Python is by writing a nice piece of code to run a Google-like search of a string ‘foo bar baz’ on a number of columns (attributes) of a table (model), finding matches of any of the keywords in the search on any column.
def str_query(query, table, columns): """ Search selected columns in a table for strings separated by spaces. """ from sqlobject import (LIKE, OR) # Target query: tablename.select(OR(LIKE(table.q.foo, '%bar%'), ...)) args = [LIKE(getattr(table.q, col), '%%%s%%' % tok) for tok in str(query).split(' ') for col in columns ] return table.select(OR(*args))
If that code could have been more beautiful, please fire away suggestions.
So, now it should be fairly easy to implement a “Search” box in Transifex returning projects with some of the keywords in their name or description.
$ tg-admin shell >>> from foo import str_query >>> query = 'translation website fedora' >>> columns = ['name', 'description'] >>> for m in str_query(query, Module, columns): ... print m.name revisor fedora-web fedorahosted-web docs-about-fedora docs-translation-quick-start-guide fas
