Login

Snippets by bobwaycott

Snippet List

Dynamic query builder with AND/OR

I recently had a need to build an iTunes style filtered search -- a user can add/subtract any number of filters whereby the are offered selects for fields they want to search, what type of search they wish to perform on that field (i.e., equals, contains, etc.), and then enter a value to search. Finally, they are provided the option to search all or any of the created filters. To keep things simple, I created this dynamic query builder. It takes a Model, plus lists of fields, types, values, and the chosen operator (and/or). Then, it constructs actual Q objects for each, performing a small sanity check to ensure a blank value has not been passed in. In the end, it returns either a filtered QuerySet or an empty result set to ensure that we can at least provide a message back to the user if nothing comes of trying to build the query. One would use it like so: results = dynamic_query(ModelName, fields_list, types_list, values_list, operator) if results: # do something else: # do something else

  • dynamic-query-builder
  • and-or-query-builder
Read More

bobwaycott has posted 1 snippet.