Python sqlalchemy.orm.ColumnProperty() Examples

The following are 9 code examples of sqlalchemy.orm.ColumnProperty(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.orm , or try the search function .
Example #1
Source File: bag.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, columns: Mapping[str, ColumnProperty]):
        """ Init columns

        :param columns: Model columns
        """
        super(ColumnsBag, self).__init__(columns)

        # More info about columns based on their type
        self._array_column_names = frozenset(name
                                             for name, col in self._columns.items()
                                             if _is_column_array(col))
        self._json_column_names =  frozenset(name
                                             for name, col in self._columns.items()
                                             if _is_column_json(col)) 
Example #2
Source File: bag.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __getitem__(self, name: str) -> Union[ColumnProperty, BinaryExpression]:
        column_name, path = _dot_notation(name)
        col = super(DotColumnsBag, self).__getitem__(column_name)
        # JSON path
        if path:
            if self.is_column_json(column_name):
                col = col[path].astext
            else:
                raise KeyError(name)
        return col 
Example #3
Source File: bag.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_column(self, name: str) -> ColumnProperty:
        """ Get a column, not a JSON path """
        return self[get_plain_column_name(name)] 
Example #4
Source File: bag.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, relationships: Mapping[str, ColumnProperty]):
        self._rel_bag = RelationshipsBag(relationships)

        #: Dot-notation mapped to columns: 'rel.col' => Column
        related_columns = {}
        #: Dot-notation mapped to target models: 'rel.col' => Model, and 'rel' => Model
        rel_col_2_model = {}

        # Collect columns from every relation
        for rel_name, relation in self._rel_bag:
            # Get the model
            model = relation.property.mapper.class_
            rel_col_2_model[rel_name] = model

            # Get the columns
            ins = inspect(model)
            cols = _get_model_columns(model, ins)  # TODO: support more attr types? hybrid? association proxy?

            # Remember all of them, using dot-notation
            for col_name, col in cols.items():
                key = '{}.{}'.format(rel_name, col_name)
                related_columns[key] = col
                rel_col_2_model[key] = model

        # Now, when we have enough information, call super().__init__
        # It will initialize:
        # `._columns`,
        # `._column_names`,
        # `._array_column_names`,
        # `._json_column_names`
        # Keep in mind that all of them are RELATED COLUMNS
        super(DotRelatedColumnsBag, self).__init__(related_columns)

        #: A mapping of related column names to target models
        #self._column_name_to_related_model = rel_col_2_model  # unused 
Example #5
Source File: bag.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __getitem__(self, name: str) -> Union[ColumnProperty, BinaryExpression]:
        return self._fake_columns[get_plain_column_name(name)] 
Example #6
Source File: __init__.py    From okcupyd with MIT License 5 votes vote down vote up
def columns(cls):
        return [prop for prop in class_mapper(cls).iterate_properties
                if isinstance(prop, ColumnProperty)] 
Example #7
Source File: enums.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def enum_for_field(obj_type, field_name):
    """Return the Graphene Enum type for the specified Graphene field."""
    from .types import SQLAlchemyObjectType

    if not isinstance(obj_type, type) or not issubclass(obj_type, SQLAlchemyObjectType):
        raise TypeError(
            "Expected SQLAlchemyObjectType, but got: {!r}".format(obj_type))
    if not field_name or not isinstance(field_name, six.string_types):
        raise TypeError(
            "Expected a field name, but got: {!r}".format(field_name))
    registry = obj_type._meta.registry
    orm_field = registry.get_orm_field_for_graphene_field(obj_type, field_name)
    if orm_field is None:
        raise TypeError("Cannot get {}.{}".format(obj_type._meta.name, field_name))
    if not isinstance(orm_field, ColumnProperty):
        raise TypeError(
            "{}.{} does not map to model column".format(obj_type._meta.name, field_name)
        )
    column = orm_field.columns[0]
    sa_enum = column.type
    if not isinstance(sa_enum, SQLAlchemyEnumType):
        raise TypeError(
            "{}.{} does not map to enum column".format(obj_type._meta.name, field_name)
        )
    enum = registry.get_graphene_enum_for_sa_enum(sa_enum)
    if not enum:
        fallback_name = obj_type._meta.name + to_type_name(field_name)
        enum = _convert_sa_to_graphene_enum(sa_enum, fallback_name)
        registry.register_enum(sa_enum, enum)
    return enum 
Example #8
Source File: helpers.py    From planespotter with MIT License 5 votes vote down vote up
def primary_key_names(model):
    """Returns all the primary keys for a model."""
    return [key for key, field in inspect.getmembers(model)
            if isinstance(field, QueryableAttribute)
            and isinstance(field.property, ColumnProperty)
            and field.property.columns[0].primary_key] 
Example #9
Source File: alchemy.py    From flask-rest-jsonapi with MIT License 5 votes vote down vote up
def apply_nested_fields(self, data, obj):
        nested_fields_to_apply = []
        nested_fields = get_nested_fields(self.resource.schema, model_field=True)
        for key, value in data.items():
            if key in nested_fields:
                nested_field_inspection = inspect(getattr(obj.__class__, key))

                if not isinstance(nested_field_inspection, QueryableAttribute):
                    raise InvalidType("Unrecognized nested field type: not a queryable attribute.")

                if isinstance(nested_field_inspection.property, RelationshipProperty):
                    nested_model = getattr(obj.__class__, key).property.mapper.class_

                    if isinstance(value, list):
                        nested_objects = []

                        for identifier in value:
                            nested_object = nested_model(**identifier)
                            nested_objects.append(nested_object)

                        nested_fields_to_apply.append({'field': key, 'value': nested_objects})
                    else:
                        nested_fields_to_apply.append({'field': key, 'value': nested_model(**value)})
                elif isinstance(nested_field_inspection.property, ColumnProperty):
                    nested_fields_to_apply.append({'field': key, 'value': value})
                else:
                    raise InvalidType("Unrecognized nested field type: not a RelationshipProperty or ColumnProperty.")

        for nested_field in nested_fields_to_apply:
            setattr(obj, nested_field['field'], nested_field['value'])