本文整理匯總了Python中sqlalchemy.sql.or_方法的典型用法代碼示例。如果您正苦於以下問題:Python sql.or_方法的具體用法?Python sql.or_怎麽用?Python sql.or_使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sqlalchemy.sql
的用法示例。
在下文中一共展示了sql.or_方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_user_filters
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def get_user_filters(user):
clauses = []
sfq = db.session.query(SampleFilter)
clauses.append(SampleFilter.user_id == user.user_id)
if not user.is_admin:
clauses.append(SampleFilter.is_public == True)
sfq.filter(or_(*clauses))
sfs = sfq.all()
data = [
{
"name": x.sample_filter_name,
"set": x.sample_filter_tag,
"id": x.sample_filter_id,
"filters": json.loads(x.sample_filter_data),
}
for x in sfs
]
return data
示例2: _term_eval
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def _term_eval(term, column_variable, column_key):
if term["type"].lower() == "conjunction":
return and_(*((_term_eval(t, column_variable, column_key) for t in term["terms"])))
elif term["type"].lower() == "disjunction":
return or_(*((_term_eval(t, column_variable, column_key) for t in term["terms"])))
elif term["type"].lower() == "literal":
if "key" in term and term["key"]:
key_operator = term.get("key_operator", "IN")
if key_operator is None or key_operator == "IN":
key_condition = column_key.in_(term["key"])
elif key_operator=="ILIKE":
key_condition = or_(*(column_key.ilike(pattern) for pattern in term["key"]))
return and_(column_variable==term["variable"], key_condition)
else:
return column_variable==term["variable"]
示例3: monitor_dashboard
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def monitor_dashboard():
docs = [x.id for x in Document.query
.filter(or_(
Document.created_by_user_id == current_user.id,
Document.checked_by_user_id == current_user.id
))
.order_by(Document.created_at.desc()).limit(30)]
docs = Document.query\
.options(
joinedload('created_by'),
joinedload('sources'),
joinedload('topic'),
joinedload('medium'),
)\
.filter(Document.id.in_(docs))\
.order_by(Document.created_at.desc())
doc_groups = []
for date, group in groupby(docs, lambda d: d.created_at.date()):
doc_groups.append([date, list(group)])
return render_template('dashboard/monitor.haml',
doc_groups=doc_groups)
示例4: find_problem_people
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def find_problem_people(self):
"""
Return a list of Person instances for people sources that lack
a race, gender or affiliation.
"""
rows = db.session.query(
DocumentSource.person_id,
func.count(1).label('count')
)\
.join(Person, Person.id == DocumentSource.person_id)\
.filter(DocumentSource.person_id != None)\
.filter(DocumentSource.doc_id.in_(self.doc_ids))\
.filter(or_(
Person.race_id == None,
Person.gender_id == None,
Person.affiliation_id == None))\
.group_by(DocumentSource.person_id)\
.order_by(desc('count'))\
.limit(20)\
.all()
return self._lookup_people([r[0] for r in rows]).values()
示例5: selectPayBtn_clicked
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def selectPayBtn_clicked(self, sender):
self.sltCheqListStore.clear()
query = self.session.query(Cheque) . filter(or_(
Cheque.chqStatus == 3, Cheque.chqStatus == 6)).filter(Cheque.chqDelete == False)
cheqlist = query.all()
numcheqs = 0
for cheq in cheqlist:
numcheqs += 1
order = utility.LN(numcheqs, False)
ID = utility.LN(cheq.chqId)
amount = utility.LN(cheq.chqAmount)
wrtDate = dateentry.dateToString(cheq.chqWrtDate)
dueDate = dateentry.dateToString(cheq.chqDueDate)
status = self.chequeStatus[cheq.chqStatus]
bank = self.bankaccounts_class.get_bank_name(cheq.chqAccount)
customer = self.session.query(Customers) .filter(
Customers.custId == cheq.chqCust).first()
if customer != None:
customer = customer.custName
else:
continue
self.sltCheqListStore.append((ID, order, customer, amount, wrtDate, dueDate, bank,
cheq.chqSerial, status, cheq.chqDesc))
self.chqSltWindow.show_all()
示例6: _sql_crit
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def _sql_crit(expression, value):
"""Produce an equality expression against the given value.
This takes into account a value that is actually a collection
of values, as well as a value of None or collection that contains
None.
"""
values = utils.to_list(value, default=(None, ))
if len(values) == 1:
if values[0] is None:
return expression == sql.null()
else:
return expression == values[0]
elif _none_set.intersection(values):
return sql.or_(
expression == sql.null(),
_sql_crit(expression, set(values).difference(_none_set))
)
else:
return expression.in_(values)
示例7: _expr
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def _expr(self,model,model_param,model_expr):
if not isinstance(model_expr,list):
raise UliwebError("only accept array in @expr, but get '%s'"%(model_expr))
num = len(model_expr)
if (num<2 or num>3):
raise UliwebError("only accept 2 or 3 items in @expr, but get '%s'"%(model_expr))
op = model_expr[-2]
if op=='&':
if num!=3:
raise UliwebError("'&'(and) expression need 3 items, but get '%s'"%(model_expr))
c1 = self._get_filter_condition(model,model_param,model_expr[0],expr=True)
c2 = self._get_filter_condition(model,model_param,model_expr[2],expr=True)
return and_(c1,c2)
elif op=='|':
if num!=3:
raise UliwebError("'|'(or) expression need 3 items, but get '%s'"%(model_expr))
c1 = self._get_filter_condition(model,model_param,model_expr[0],expr=True)
c2 = self._get_filter_condition(model,model_param,model_expr[2],expr=True)
return or_(c1,c2)
elif op=='!':
if num!=2:
raise UliwebError("'!'(not) expression need 2 items, but get '%s'"%(model_expr))
return not_(self._get_filter_condition(model,model_param,model_expr[1],expr=True))
else:
raise UliwebError("unknown operator: '%s'"%(op))
示例8: to_python
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def to_python(self, value):
cls = self.cls
try:
return cls.query.get_or_404(int(value))
except ValueError:
pass
if not getattr(cls, "__LOOKUP_ATTRS__", False):
abort(404)
return cls.query.filter(or_(*[getattr(cls, key) == value
for key in cls.__LOOKUP_ATTRS__])
).first_or_404()
示例9: filter_visible
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def filter_visible(self, attr, remoteAttr):
filters = self._gen_filters(remoteAttr.class_, 'view')
if not filters:
return self.filter(False)
return self.filter(attr.in_(
remoteAttr.class_.query.filter(or_(*filters))
.with_entities(remoteAttr)
.subquery()
)
)
示例10: get_dashboard_data
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def get_dashboard_data(user, dashboard_id):
"""
Fetch a dashboard by ID and return the data.
"""
# Get the database row for this favourite
row = (
db.session.query(
Dashboard.dashboard_id,
Dashboard.user_id,
Dashboard.title,
Dashboard.data,
Dashboard.is_public,
Dashboard.modified_at,
Dashboard.created_at,
)
.filter(
or_(Dashboard.user_id == user.user_id, Dashboard.is_public == True),
Dashboard.dashboard_id == dashboard_id,
)
.first()
)
if row is None:
return None
# Calculate extra variables
parsed_data = json.loads(row.data)
max_height = max([d["y"] + d["height"] for d in parsed_data])
return dict(
dashboard_id=row.dashboard_id,
user_id=row.user_id,
title=row.title,
data=parsed_data,
max_height=max_height,
is_public=row.is_public,
modified_at=row.modified_at,
created_at=row.created_at,
)
示例11: text_filter
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def text_filter(query, value, table):
pairs = ((n, c) for n, c in table.c.items()
if isinstance(c.type, sa.sql.sqltypes.String))
sub_queries = []
for name, column in pairs:
do_compare = op("like", column)
sub_queries.append(do_compare(column, value))
query = query.where(or_(*sub_queries))
return query
# TODO: validate that value supplied in filter has same type as in table
# TODO: use functional style to create query
示例12: get_relationships
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def get_relationships(self, with_package=None, type=None, active=True,
direction='both'):
'''Returns relationships this package has.
Keeps stored type/ordering (not from pov of self).'''
assert direction in ('both', 'forward', 'reverse')
if with_package:
assert isinstance(with_package, Package)
from package_relationship import PackageRelationship
forward_filters = [PackageRelationship.subject==self]
reverse_filters = [PackageRelationship.object==self]
if with_package:
forward_filters.append(PackageRelationship.object==with_package)
reverse_filters.append(PackageRelationship.subject==with_package)
if active:
forward_filters.append(PackageRelationship.state==core.State.ACTIVE)
reverse_filters.append(PackageRelationship.state==core.State.ACTIVE)
if type:
forward_filters.append(PackageRelationship.type==type)
reverse_type = PackageRelationship.reverse_type(type)
reverse_filters.append(PackageRelationship.type==reverse_type)
q = meta.Session.query(PackageRelationship)
if direction == 'both':
q = q.filter(or_(
and_(*forward_filters),
and_(*reverse_filters),
))
elif direction == 'forward':
q = q.filter(and_(*forward_filters))
elif direction == 'reverse':
q = q.filter(and_(*reverse_filters))
return q.all()
示例13: exclude_topic_mutes
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def exclude_topic_mutes(conditions: List[Selectable],
user_profile: UserProfile,
stream_id: Optional[int]) -> List[Selectable]:
query = MutedTopic.objects.filter(
user_profile=user_profile,
)
if stream_id is not None:
# If we are narrowed to a stream, we can optimize the query
# by not considering topic mutes outside the stream.
query = query.filter(stream_id=stream_id)
query = query.values(
'recipient_id',
'topic_name',
)
rows = list(query)
if not rows:
return conditions
def mute_cond(row: Dict[str, Any]) -> Selectable:
recipient_id = row['recipient_id']
topic_name = row['topic_name']
stream_cond = column("recipient_id") == recipient_id
topic_cond = topic_match_sa(topic_name)
return and_(stream_cond, topic_cond)
condition = not_(or_(*list(map(mute_cond, rows))))
return conditions + [condition]
示例14: downgrade
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def downgrade():
# Add ship and pilot transformer columns back to division
op.add_column('division', sa.Column('ship_transformer', sa.PickleType))
op.add_column('division', sa.Column('pilot_transformer', sa.PickleType))
# Convert transformerrefs back to the old columns
conn = op.get_bind()
columns = [
transformerref.c.division_id,
transformerref.c.attribute_name,
transformerref.c.transformer,
]
transformer_sel = select(columns)\
.where(or_(
transformerref.c.attribute_name == 'ship_type',
transformerref.c.attribute_name == 'pilot',
))
transformer_rows = conn.execute(transformer_sel)
for division_id, attribute_name, transformer in transformer_rows:
if attribute_name == 'ship_type':
colname = 'ship'
transformer_class = evesrp.transformers.ShipTransformer
elif attribute_name == 'pilot':
colname = 'pilot'
transformer_class = evesrp.transformers.PilotTransformer
colname += '_transformer'
transformer = transformer_class(transformer.name, transformer.slug)
update_stmt = update(division)\
.where(division.c.id == division_id)\
.values({
colname: transformer
})
conn.execute(update_stmt)
transformer_rows.close()
# Drop the transformerref table. This is going to be lossy.
op.drop_table('transformerref')
示例15: find_any
# 需要導入模塊: from sqlalchemy import sql [as 別名]
# 或者: from sqlalchemy.sql import or_ [as 別名]
def find_any(query, model, kwargs):
"""
Returns a query object that allows any kwarg
to be present.
:param query:
:param model:
:param kwargs:
:return:
"""
or_args = []
for attr, value in kwargs.items():
or_args.append(or_(get_model_column(model, attr) == value))
exprs = or_(*or_args)
return query.filter(exprs)