本文整理汇总了Python中sqlalchemy.sql.expression.func.lower函数的典型用法代码示例。如果您正苦于以下问题:Python lower函数的具体用法?Python lower怎么用?Python lower使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了lower函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: order_by_name
def order_by_name(query, table, language=None, *extra_languages, **kwargs):
"""Order a query by name.
query: The query to order
table: Table of the named objects
language: The language to order names by. If None, use the
connection default.
extra_languages: Extra languages to order by, should the translations for
`language` be incomplete (or ambiguous).
name_attribute (keyword argument): the attribute to use; defaults to 'name'
Uses the identifier as a fallback ordering.
"""
name_attribute = kwargs.pop('name', 'name')
if kwargs:
raise ValueError('Unexpected keyword arguments: %s' % list(kwargs.keys()))
order_columns = []
if language is None:
query = query.outerjoin(table.names_local)
order_columns.append(func.lower(getattr(table.names_table, name_attribute)))
else:
extra_languages = (language, ) + extra_languages
for language in extra_languages:
names_table = aliased(table.names_table)
query = query.outerjoin(names_table)
query = query.filter(names_table.foreign_id == table.id)
query = query.filter(names_table.local_language_id == language.id)
order_columns.append(func.lower(getattr(names_table, name_attribute)))
order_columns.append(table.identifier)
query = query.order_by(coalesce(*order_columns))
return query
示例2: filter
def filter(self, query, q, **kwargs):
if q:
query = query.filter(
or_(func.lower(User.first_name).like(q + "%"),
func.lower(User.last_name).like(q + "%"))
)
return query
示例3: apply_filters
def apply_filters(query):
if 'filters' not in query_params:
return query
filters = query_params['filters']
for key, val in filters.items():
op, field_name = key.split('_', 1)
try:
field = getattr(cls, field_name)
except AttributeError:
log.warn('RestMixin.rest_get_list(): filter "%s=%s": unknown attribute %s',
key, val, field_name)
continue
if op == 'e':
query = query.filter(field == val)
elif op == 'n':
query = query.filter(or_(field == val, field == None))
elif op == 'l':
query = query.filter(func.lower(field).like('%' + val.lower() + '%'))
elif op == 's':
query = query.filter(func.lower(field).like(val.lower() + '%'))
else:
log.error('get_for_rest_grid: filter "%s=%s": unknown op: %s' % (key, val, op))
return query
示例4: get_filter
def get_filter(self, trans, user, column_filter):
# Parse filter to extract multiple tags.
if isinstance(column_filter, list):
# Collapse list of tags into a single string; this is redundant but effective. TODO: fix this by iterating over tags.
column_filter = ",".join(column_filter)
raw_tags = trans.app.tag_handler.parse_tags(column_filter.encode("utf-8"))
clause_list = []
for name, value in raw_tags.items():
if name:
# Filter by individual's tag names.
clause_list.append(
self.model_class.tags.any(
and_(
func.lower(self.model_tag_association_class.user_tname).like("%" + name.lower() + "%"),
self.model_tag_association_class.user == user,
)
)
)
if value:
# Filter by individual's tag values.
clause_list.append(
self.model_class.tags.any(
and_(
func.lower(self.model_tag_association_class.user_value).like("%" + value.lower() + "%"),
self.model_tag_association_class.user == user,
)
)
)
return and_(*clause_list)
示例5: sort
def sort( self, trans, query, ascending, column_name=None ):
""" Sort column using case-insensitive alphabetical sorting on item's username. """
if ascending:
query = query.order_by( func.lower( self.model_class.username ).asc() )
else:
query = query.order_by( func.lower( self.model_class.username ).desc() )
return query
示例6: exact_name_lookup
def exact_name_lookup(card, edition=None):
cquery = session.query(CardInfo).filter(func.lower(CardInfo.name)==func.lower(card))
if edition is not None:
cquery = cquery.filter(func.lower(CardInfo.edition)==func.lower(edition))
cards = cquery.all();
if cards == []:
print 'not found:', card
return cards[0:1]
示例7: quicksearch
def quicksearch(request):
message = None
query = DBSession.query(Languoid)
term = request.params['search'].strip()
titlecase = term.istitle()
term = term.lower()
params = {'iso': '', 'country': '',
'name': '', 'namequerytype': 'part', 'multilingual': ''}
if not term:
query = None
elif len(term) < 3:
query = None
message = ('Please enter at least four characters for a name search '
'or three characters for an iso code')
elif len(term) == 3 and not titlecase:
query = query.filter(Languoid.identifiers.any(
type=IdentifierType.iso.value, name=term))
kind = 'ISO 639-3'
elif len(term) == 8 and GLOTTOCODE_PATTERN.match(term):
query = query.filter(Languoid.id == term)
kind = 'Glottocode'
else:
_query = query.filter(func.lower(Languoid.name) == term)
if DBSession.query(_query.exists()).scalar():
query = _query
else:
query = query.filter(or_(
func.lower(Languoid.name).contains(term),
Languoid.identifiers.any(and_(
Identifier.type == u'name',
Identifier.description == Languoid.GLOTTOLOG_NAME,
func.lower(Identifier.name).contains(term)))))
kind = 'name part'
params['name'] = term
if query is None:
languoids = []
else:
languoids = query.order_by(Languoid.name)\
.options(joinedload(Languoid.family)).all()
if not languoids:
term_pre = HTML.kbd(term, style='white-space: pre')
message = 'No matching languoids found for %s "' % kind + term_pre + '"'
elif len(languoids) == 1:
raise HTTPFound(request.resource_url(languoids[0]))
map_, icon_map, family_map = get_selected_languages_map(request, languoids)
layer = list(map_.get_layers())[0]
if not layer.data['features']:
map_ = None
countries = json.dumps(['%s (%s)' % (c.name, c.id) for c in
DBSession.query(Country).order_by(Country.description)])
return {'message': message, 'params': params, 'languoids': languoids,
'map': map_, 'countries': countries}
示例8: json_search
def json_search():
query = request.args['query']
return jsonify(users=map(
lambda u: {"id": u.id, "name": u.name},
session.query(User.id, User.name).filter(or_(
func.lower(User.name).like(func.lower(u"%{}%".format(query))),
User.id.like(u"{}%".format(query))
))
))
示例9: data
def data(self, *args, **kw):
security = get_service("security")
length = int(kw.get("iDisplayLength", 0))
start = int(kw.get("iDisplayStart", 0))
sort_dir = kw.get("sSortDir_0", "asc")
echo = int(kw.get("sEcho", 0))
search = kw.get("sSearch", "").replace("%", "").strip().lower()
end = start + length
query = Group.query.options(sa.orm.noload("*"))
total_count = query.count()
if search:
# TODO: gérer les accents
query = query.filter(func.lower(Group.name).like("%" + search + "%"))
count = query.count()
columns = [func.lower(Group.name)]
direction = asc if sort_dir == "asc" else desc
order_by = list(map(direction, columns))
# sqlite does not support 'NULLS FIRST|LAST' in ORDER BY clauses
engine = query.session.get_bind(Group.__mapper__)
if engine.name != "sqlite":
order_by[0] = nullslast(order_by[0])
query = query.order_by(*order_by).add_columns(Group.members_count)
groups = query.slice(start, end).all()
data = []
for group, members_count in groups:
# TODO: this should be done on the browser.
group_url = url_for(".groups_group", group_id=group.id)
name = html.escape(group.name or "")
roles = [r for r in security.get_roles(group) if r.assignable]
columns = [
f'<a href="{group_url}">{name}</a>',
str(members_count or 0),
render_template_string(
"""{%- for role in roles %}
<span class="badge badge-default">{{ role }}</span>
{%- endfor %}""",
roles=roles,
),
"\u2713" if group.public else "",
]
data.append(columns)
return {
"sEcho": echo,
"iTotalRecords": total_count,
"iTotalDisplayRecords": count,
"aaData": data,
}
示例10: data
def data(self, *args, **kw):
security = current_app.services['security']
length = int(kw.get("iDisplayLength", 0))
start = int(kw.get("iDisplayStart", 0))
sort_dir = kw.get("sSortDir_0", "asc")
echo = int(kw.get("sEcho", 0))
search = kw.get("sSearch", "").replace("%", "").strip().lower()
end = start + length
q = Group.query \
.options(sa.orm.noload('*'))
total_count = q.count()
if search:
# TODO: gérer les accents
q = q.filter(func.lower(Group.name).like("%" + search + "%"))
count = q.count()
columns = [func.lower(Group.name)]
direction = asc if sort_dir == 'asc' else desc
order_by = map(direction, columns)
# sqlite does not support 'NULLS FIRST|LAST' in ORDER BY clauses
engine = q.session.get_bind(Group.__mapper__)
if engine.name != 'sqlite':
order_by[0] = nullslast(order_by[0])
q = q.order_by(*order_by) \
.add_columns(Group.members_count)
groups = q.slice(start, end).all()
data = []
for group, members_count in groups:
# TODO: this should be done on the browser.
group_url = url_for(".groups_group", group_id=group.id)
name = escape(getattr(group, "name") or "")
roles = [r for r in security.get_roles(group) if r.assignable]
columns = []
columns.append(
u'<a href="{url}">{name}</a>'.format(url=group_url, name=name)
)
columns.append(unicode(members_count or 0))
columns.append(render_template_string(
u'''{%- for role in roles %}
<span class="badge badge-default">{{ role }}</span>
{%- endfor %}''',
roles=roles))
columns.append(u'\u2713' if group.public else u'')
data.append(columns)
return {
"sEcho": echo,
"iTotalRecords": total_count,
"iTotalDisplayRecords": count,
"aaData": data,
}
示例11: rss_category
def rss_category(self):
category = func.lower(self.request.matchdict['category'])
query = self.Entry.get_all_active(self.request)
query = query.join(self.Category)
query = query.filter(
func.lower(self.Category.title) == category
)
entries = query.all()
return self.get_rss_data(entries)
示例12: wildcard_handler
def wildcard_handler(col, wc_term):
if wc_term.startswith('*') and not wc_term.endswith('*'):
#postfix == endswith
wc_term = remove_prefix(wc_term, prefix='*')
return func.lower(col).endswith(wc_term)
elif wc_term.startswith('*') and wc_term.endswith('*'):
#wildcard == ilike
wc_term = remove_prefix(wc_term, prefix='*')
wc_term = remove_suffix(wc_term, suffix='*')
return func.lower(col).contains(wc_term)
示例13: search_all_members
def search_all_members(self, query, limit=10):
"""
Searches for members from this place or places below this by name, phone or email.
:param query: search query
:return: List of object Member
"""
like_q = "%{0}%".format(query.lower())
q1 = Member.query.filter(
place_parents.c.child_id == Member.place_id,
place_parents.c.parent_id == self.id,
(func.lower(Member.name).like(like_q) | Member.phone.like(like_q) | func.lower(Member.email).like(
like_q))).limit(limit)
return q1.all()
示例14: findCard
def findCard(self, card, edition=None):
cquery = datasources.database.db.session.query(CardInfo).filter(func.lower(CardInfo.name) == func.lower(card))
edition = self.getRealEditionName(edition)
if edition is not None:
cquery = cquery.filter(func.lower(CardInfo.edition) == func.lower(edition))
cards = cquery.all()
if not cards:
logger.warn('not found: %s', card)
if len(cards) > 1 and self.forceSingleMatch:
logger.warn('more than one matches found for card: {card}, selecting first match: {ed}'.format(card=card,
ed=cards[0].edition))
return cards[0:1]
return cards
示例15: get_by_name_or_email
def get_by_name_or_email(self, name_or_email):
"""Get a user by name or email
"""
User = tables.User
user = (
self.session
.query(User)
.filter(or_(
func.lower(User.user_name) == name_or_email.lower(),
func.lower(User.email) == name_or_email.lower()
))
)
return user.first()