Skip to content

Instantly share code, notes, and snippets.

@douglatornell
Created June 28, 2013 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglatornell/5887821 to your computer and use it in GitHub Desktop.
Save douglatornell/5887821 to your computer and use it in GitHub Desktop.
dwgLINQ search code
@staticmethod
def search(params):
"""Return an iterator that yields :class:`Drawing` objects populated
with the data for the drawings that match the search parameters.
:arg params: Search parameters in key-value pairs from search form
on drawings page.
:type params: dict
"""
filters = []
for field in 'dwg_id title notes'.split():
filters.append(Drawing._text_filter(params, field))
filters.append(Drawing._status_filter(params.get('status')))
return (
DBSession.query(Drawing)
.filter(*[f for f in filters if f is not None])
.order_by(Drawing.sort_id)
)
@staticmethod
def _text_filter(params, key):
def begins(value):
return getattr(Drawing, key).like(value + '%')
def ends(value):
return getattr(Drawing, key).like('%' + value)
def in_(value):
return getattr(Drawing, key).like('%' + value + '%')
def not_in_(value):
return ~getattr(Drawing, key).like('%' + value + '%')
filters = {
'begins': begins,
'ends': ends,
'in': in_,
'not in': not_in_,
}
value = params.get(key, '')
if value:
condition = params.get(key + '_condition', '')
return filters[condition](value)
@staticmethod
def _status_filter(status):
return (
Drawing.status.like('%') if status == 'any'
else Drawing.status == status
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment