Python sqlalchemy.ext.associationproxy.AssociationProxy() Examples

The following are 9 code examples of sqlalchemy.ext.associationproxy.AssociationProxy(). 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.ext.associationproxy , or try the search function .
Example #1
Source File: helpers.py    From planespotter with MIT License 6 votes vote down vote up
def get_field_type(model, fieldname):
    """Helper which returns the SQLAlchemy type of the field.

    """
    field = getattr(model, fieldname)
    if isinstance(field, ColumnElement):
        fieldtype = field.type
    else:
        if isinstance(field, AssociationProxy):
            field = field.remote_attr
        if hasattr(field, 'property'):
            prop = field.property
            if isinstance(prop, RelProperty):
                return None
            fieldtype = prop.columns[0].type
        else:
            return None
    return fieldtype 
Example #2
Source File: helpers.py    From planespotter with MIT License 6 votes vote down vote up
def is_like_list(instance, relation):
    """Returns ``True`` if and only if the relation of `instance` whose name is
    `relation` is list-like.

    A relation may be like a list if, for example, it is a non-lazy one-to-many
    relation, or it is a dynamically loaded one-to-many.

    """
    if relation in instance._sa_class_manager:
        return instance._sa_class_manager[relation].property.uselist
    elif hasattr(instance, relation):
        attr = getattr(instance._sa_instance_state.class_, relation)
        if hasattr(attr, 'property'):
            return attr.property.uselist
    related_value = getattr(type(instance), relation, None)
    if isinstance(related_value, AssociationProxy):
        local_prop = related_value.local_attr.prop
        if isinstance(local_prop, RelProperty):
            return local_prop.uselist
    return False 
Example #3
Source File: _model_factory.py    From flask-react-spa with MIT License 6 votes vote down vote up
def maybe_convert_values(self, model_class, data):
        ret = data.copy()
        for col_name, value in data.items():
            col = getattr(model_class, col_name)
            if isinstance(col, AssociationProxy) or col.impl.uses_objects:
                ret[col_name] = self.convert_identifiers(value)
            elif not hasattr(col, 'type'):
                continue
            elif isinstance(col.type, Date):
                if value in ('today', 'now', 'utcnow'):
                    ret[col_name] = utcnow().date
                else:
                    ret[col_name] = parse_datetime(value).date
            elif isinstance(col.type, DateTime):
                if value in ('now', 'utcnow'):
                    ret[col_name] = utcnow()
                elif not isinstance(value, datetime.datetime):
                    ret[col_name] = parse_datetime(value)
        return ret 
Example #4
Source File: bag.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_column_array(self, name: str) -> bool:
        # Well, even though this column is clearly an array, it does not behave like one when thought of in terms of
        # Postgres operators, because the underlying comparison is done to a scalar column.
        # Example: AssociationProxy to User.name will use the `name` column for comparisons, which is scalar!
        return False 
Example #5
Source File: bag.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_model_association_proxies(model, ins):
    """ Get a dict of model association_proxy attributes """
    # Ignore AssociationProxy attrs for SA 1.2.x
    if SA_12:
        warnings.warn('MongoSQL only supports AssociationProxy columns with SqlAlchemy 1.3.x')
        return {}

    return {name: getattr(model, name)
            for name, c in ins.all_orm_descriptors.items()
            if not name.startswith('_')
            and isinstance(c, AssociationProxy)} 
Example #6
Source File: collection_view.py    From pyramid-jsonapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def related_query(self, obj_id, relationship, full_object=True):
        """Construct query for related objects.

        Parameters:
            obj_id (str): id of an item in this view's collection.

            relationship: the relationship object to get related objects from.
                This can be a RelationshipProperty or AssociationProxy object.

            related_to (model class or None): the class the relationship is
                coming from. AssociationProxy relationships use this. It
                defaults to ``None``, which is interpreted as self.model.

            full_object (bool): if full_object is ``True``, query for all
                requested columns (probably to build resource objects). If
                full_object is False, only query for the key column (probably
                to build resource identifiers).

        Returns:
            sqlalchemy.orm.query.Query: query which will fetch related
            object(s).
        """
        if isinstance(relationship.obj, AssociationProxy):
            query = self.association_proxy_query(
                obj_id, relationship, full_object=full_object
            )
        else:
            query = self.standard_relationship_query(
                obj_id, relationship, full_object=full_object
            )
        return query 
Example #7
Source File: helpers.py    From planespotter with MIT License 5 votes vote down vote up
def get_related_model(model, relationname):
    """Gets the class of the model to which `model` is related by the attribute
    whose name is `relationname`.

    """
    if hasattr(model, relationname):
        attr = getattr(model, relationname)
        if hasattr(attr, 'property') \
                and isinstance(attr.property, RelProperty):
            return attr.property.mapper.class_
        if isinstance(attr, AssociationProxy):
            return get_related_association_proxy_model(attr)
    return None 
Example #8
Source File: mixins.py    From incubator-ariatosca with Apache License 2.0 5 votes vote down vote up
def _iter_association_proxies(cls):
        for col, value in vars(cls).items():
            if isinstance(value, associationproxy.AssociationProxy):
                yield col 
Example #9
Source File: search.py    From planespotter with MIT License 4 votes vote down vote up
def _sub_operator(model, argument, fieldname):
    """Recursively calls :func:`QueryBuilder._create_operation` when argument
    is a dictionary of the form specified in :ref:`search`.

    This function is for use with the ``has`` and ``any`` search operations.

    """
    if isinstance(model, InstrumentedAttribute):
        submodel = model.property.mapper.class_
    elif isinstance(model, AssociationProxy):
        submodel = get_related_association_proxy_model(model)
    else:  # TODO what to do here?
        pass
    if isinstance(argument, dict):
        fieldname = argument['name']
        operator = argument['op']
        argument = argument.get('val')
        relation = None
        if '__' in fieldname:
            fieldname, relation = fieldname.split('__')
        return QueryBuilder._create_operation(submodel, fieldname, operator,
                                              argument, relation)
    # Support legacy has/any with implicit eq operator
    return getattr(submodel, fieldname) == argument


#: The mapping from operator name (as accepted by the search method) to a
#: function which returns the SQLAlchemy expression corresponding to that
#: operator.
#:
#: Each of these functions accepts either one, two, or three arguments. The
#: first argument is the field object on which to apply the operator. The
#: second argument, where it exists, is either the second argument to the
#: operator or a dictionary as described below. The third argument, where it
#: exists, is the name of the field.
#:
#: For functions that accept three arguments, the second argument may be a
#: dictionary containing ``'name'``, ``'op'``, and ``'val'`` mappings so that
#: :func:`QueryBuilder._create_operation` may be applied recursively. For more
#: information and examples, see :ref:`search`.
#:
#: Some operations have multiple names. For example, the equality operation can
#: be described by the strings ``'=='``, ``'eq'``, ``'equals'``, etc.