当前位置: 首页>>代码示例>>Python>>正文


Python sql.or_方法代码示例

本文整理汇总了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 
开发者ID:ewels,项目名称:MegaQC,代码行数:20,代码来源:utils.py

示例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"] 
开发者ID:ActiDoo,项目名称:gamification-engine,代码行数:18,代码来源:formular.py

示例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) 
开发者ID:Code4SA,项目名称:mma-dexter,代码行数:26,代码来源:dashboard.py

示例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() 
开发者ID:Code4SA,项目名称:mma-dexter,代码行数:24,代码来源:sources.py

示例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() 
开发者ID:Jooyeshgar,项目名称:amir,代码行数:26,代码来源:payments.py

示例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) 
开发者ID:openstack,项目名称:oslo.db,代码行数:24,代码来源:update_match.py

示例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)) 
开发者ID:zhangchunlin,项目名称:uliweb-apijson,代码行数:27,代码来源:views.py

示例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() 
开发者ID:beavyHQ,项目名称:beavy,代码行数:15,代码来源:url_converters.py

示例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()
            )
        ) 
开发者ID:beavyHQ,项目名称:beavy,代码行数:13,代码来源:access_query.py

示例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,
    ) 
开发者ID:ewels,项目名称:MegaQC,代码行数:39,代码来源:utils.py

示例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 
开发者ID:aio-libs,项目名称:aiohttp_admin,代码行数:16,代码来源:sa_utils.py

示例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() 
开发者ID:italia,项目名称:daf-recipes,代码行数:33,代码来源:package.py

示例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] 
开发者ID:zulip,项目名称:zulip,代码行数:32,代码来源:topic_mutes.py

示例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') 
开发者ID:paxswill,项目名称:evesrp,代码行数:37,代码来源:4280bf2417c_.py

示例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) 
开发者ID:Netflix,项目名称:lemur,代码行数:17,代码来源:database.py


注:本文中的sqlalchemy.sql.or_方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。