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


Python expression.cast方法代码示例

本文整理汇总了Python中sqlalchemy.sql.expression.cast方法的典型用法代码示例。如果您正苦于以下问题:Python expression.cast方法的具体用法?Python expression.cast怎么用?Python expression.cast使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sqlalchemy.sql.expression的用法示例。


在下文中一共展示了expression.cast方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: preprocess_column_and_value

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def preprocess_column_and_value(self):
        """ Preprocess the column and the value

            Certain operations will only work if the types are cast correctly.
            This is where it happens.
        """
        col, val = self.column, self.value

        # Case 1. Both column and value are arrays
        if self.is_column_array() and self.is_value_array():
            # Cast the value to ARRAY[] with the same type that the column has
            # Only in this case Postgres will be able to handles them both
            val = cast(pg.array(val), pg.ARRAY(col.type.item_type))

        # Case 2. JSON column
        if self.is_column_json():
            # This is the type to which JSON column is coerced: same as `value`
            # Doc: "Suggest a type for a `coerced` Python value in an expression."
            coerce_type = col.type.coerce_compared_value('=', val)  # HACKY: use sqlalchemy type coercion
            # Now, replace the `col` used in operations with this new coerced expression
            col = cast(col, coerce_type)

        # Done
        self.column_expression = col
        self.value_expression = val 
开发者ID:kolypto,项目名称:py-mongosql,代码行数:27,代码来源:filter.py

示例2: compile

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def compile(self):
        # Json column?
        if self.is_column_json:
            # PostgreSQL always returns text values from it, and for aggregation we usually need numbers :)
            column = cast(self.column, Float)
        else:
            # Simply use
            column = self.column

        # Now, handle the operator, and apply it to the expression
        if self.operator == '$max':
            stmt = func.max(column)
        elif self.operator == '$min':
            stmt = func.min(column)
        elif self.operator == '$avg':
            stmt = func.avg(column)
        elif self.operator == '$sum':
            stmt = func.sum(column)
        else:
            raise InvalidQueryError('Aggregate: unsupported operator "{}"'.format(self.operator))
        return self.labeled_expression(stmt) 
开发者ID:kolypto,项目名称:py-mongosql,代码行数:23,代码来源:aggregate.py

示例3: _serialize_and_update_indexes

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def _serialize_and_update_indexes(self,obj,collection,d,for_update = False):

        pk_type = self._index_fields[collection]['pk']['type']

        for index_field,index_params in self._index_fields[collection].items():
            try:
                if for_update:
                    value = obj[index_field]
                else:
                    value = get_value(obj,index_field)
                if value is None:
                    if not index_params['field'].nullable:
                        raise ValueError("Value for %s is `None`, but this is a mandatory field!" % index_field)
                    d[index_params['column']] = null()
                else:
                    d[index_params['column']] = expression.cast(value,index_params['type'])
            except KeyError:
                if for_update:
                    continue
                if index_params['field'].default is not None:
                    d[index_params['column']] = index_params['field'].default
                elif not index_params['field'].nullable:
                    raise ValueError("No value for %s given, but this is a mandatory field!" % index_field)
                else:
                    d[index_params['column']] = null() 
开发者ID:adewes,项目名称:blitzdb,代码行数:27,代码来源:backend.py

示例4: test_paginate_with_boolean_sort

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def test_paginate_with_boolean_sort(self):
        s = Session()
        q = s.query(FakeTable)
        q = utils.paginate_query(q, FakeTable, 5, ['enabled'],
                                 sort_dirs=['asc'],
                                 marker=FakeTable(user_id='hello',
                                                  enabled=False))
        expected_core_sql = (
            select([FakeTable]).
            order_by(sqlalchemy.asc(FakeTable.enabled)).
            where(cast(FakeTable.enabled, Integer) > 0).
            limit(5)
        )

        self.assertEqual(
            str(expected_core_sql.compile()),
            str(q.statement.compile())
        ) 
开发者ID:openstack,项目名称:oslo.db,代码行数:20,代码来源:test_utils.py

示例5: chosen

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def chosen(self):
        """Retrieve chosen via property1."""
        return cast(self.property1, Boolean) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:5,代码来源:models.py

示例6: generation

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def generation(self):
        """Make generation queryable."""
        return cast(self.property2, Integer) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:5,代码来源:models.py

示例7: score

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def score(self):
        """Make score queryable."""
        return cast(self.property3, Integer) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:5,代码来源:models.py

示例8: proportion

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def proportion(self):
        """Make proportion queryable."""
        return cast(self.property4, Float) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:5,代码来源:models.py

示例9: generation

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def generation(self):
        """Make generation queryable."""
        from sqlalchemy import Integer
        from sqlalchemy.sql.expression import cast

        return cast(self.property2, Integer) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:8,代码来源:test_networks.py

示例10: age

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def age(cls, reference):
        """
        Person's age relative to a reference date.

        :param reference: Date object of reference date.
        :return: Integer value of person's age.
        """
        return cast((reference - cls.birth_date)/365.25 - 0.5, Integer) 
开发者ID:soccermetrics,项目名称:marcotti,代码行数:10,代码来源:personnel.py

示例11: get_queryset

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def get_queryset(self,*args,**kwargs):
        if self._queryset is None:
            relationship_table = self.params['relationship_table']
            foreign_table = self.obj.backend.get_collection_table(self.params['collection'])
            condition = relationship_table.c[self.params['pk_field_name']] \
                == expression.cast(self.obj.pk,self.params['type'])
            self._queryset = QuerySet(backend = self.obj.backend,
                                      table = foreign_table,
                                      cls = self.params['class'],
                                      joins = [(relationship_table,)],
                                      condition = condition,
                                      objects = self._objects,
                                      *args,
                                      **kwargs)
        return self._queryset 
开发者ID:adewes,项目名称:blitzdb,代码行数:17,代码来源:relations.py

示例12: get_tiles_by_quadkey

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def get_tiles_by_quadkey(prediction_id: int, quadkeys: tuple, zoom: int):
        return db.session.query(func.substr(PredictionTile.quadkey, 1, zoom).label('qaudkey'),
                                func.avg(cast(cast(PredictionTile.predictions['ml_prediction'], sqlalchemy.String),
                                         sqlalchemy.Float)).label('ml_prediction'),
                                func.avg(cast(cast(PredictionTile.predictions['osm_building_area'], sqlalchemy.String),
                                         sqlalchemy.Float)).label('osm_building_area')).filter(PredictionTile.prediction_id == prediction_id).filter(
                                             func.substr(
                                              PredictionTile.quadkey, 1, zoom).in_(quadkeys)).group_by(func.substr(PredictionTile.quadkey, 1, zoom)).all() 
开发者ID:hotosm,项目名称:ml-enabler,代码行数:10,代码来源:ml_model.py

示例13: get_aggregate_for_polygon

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def get_aggregate_for_polygon(prediction_id: int, polygon: str):
        return db.session.query(func.avg(cast(cast(PredictionTile.predictions['ml_prediction'], sqlalchemy.String), sqlalchemy.Float)).label('ml_prediction'),
                                func.avg(cast(cast(PredictionTile.predictions['osm_building_area'],
                                         sqlalchemy.String), sqlalchemy.Float)).label('osm_building_area')).filter(
            PredictionTile.prediction_id == prediction_id).filter(ST_Within(PredictionTile.centroid, ST_GeomFromText(polygon)) == 'True').one() 
开发者ID:hotosm,项目名称:ml-enabler,代码行数:7,代码来源:ml_model.py

示例14: perm

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def perm(cls) -> str:  # pylint: disable=no-self-argument
        return (
            "[" + cls.database_name + "].(id:" + expression.cast(cls.id, String) + ")"
        ) 
开发者ID:apache,项目名称:incubator-superset,代码行数:6,代码来源:core.py

示例15: perm

# 需要导入模块: from sqlalchemy.sql import expression [as 别名]
# 或者: from sqlalchemy.sql.expression import cast [as 别名]
def perm(cls) -> str:  # pylint: disable=no-self-argument
        return "[" + cls.cluster_name + "].(id:" + expression.cast(cls.id, String) + ")" 
开发者ID:apache,项目名称:incubator-superset,代码行数:4,代码来源:models.py


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