Python sqlalchemy.orm.RelationshipProperty() Examples
The following are 19
code examples of sqlalchemy.orm.RelationshipProperty().
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: helpers.py From planespotter with MIT License | 6 votes |
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 #2
Source File: helpers.py From planespotter with MIT License | 6 votes |
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 #3
Source File: meta_options.py From flask-unchained with MIT License | 6 votes |
def contribute_to_class(self, mcs_args: McsArgs, relationships): if mcs_args.Meta.abstract: return discovered_relationships = {} def discover_relationships(d): for k, v in d.items(): if isinstance(v, RelationshipProperty): discovered_relationships[v.argument] = k if v.backref and mcs_args.Meta.lazy_mapped: raise NotImplementedError( f'Discovered a lazy-mapped backref `{k}` on ' f'`{mcs_args.qualname}`. Currently this ' 'is unsupported; please use `db.relationship` with ' 'the `back_populates` kwarg on both sides instead.') for base in mcs_args.bases: discover_relationships(vars(base)) discover_relationships(mcs_args.clsdict) relationships.update(discovered_relationships)
Example #4
Source File: test_api.py From MegaQC with GNU General Public License v3.0 | 6 votes |
def object_as_dict(obj, relationships=False): """ Converts an SQLAlchemy instance to a dictionary. :param relationships: If true, also include relationships in the output dict """ properties = inspect(obj).mapper.all_orm_descriptors if not relationships: properties = { key: value for key, value in properties.items() if not hasattr(value, "prop") or not isinstance(value.prop, RelationshipProperty) } return {key: getattr(obj, key) for key, value in properties.items()}
Example #5
Source File: models.py From lux with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _should_exclude_field(column, fields=None, exclude=None, include_related=None): if fields and column.key not in fields: return True if exclude and column.key in exclude: return True if isinstance(column, RelationshipProperty) and not include_related: return True return False
Example #6
Source File: models.py From incubator-superset with Apache License 2.0 | 5 votes |
def datasource(self) -> RelationshipProperty: return self.table
Example #7
Source File: models.py From incubator-superset with Apache License 2.0 | 5 votes |
def slices(self) -> RelationshipProperty: return relationship( "Slice", primaryjoin=lambda: and_( foreign(Slice.datasource_id) == self.id, foreign(Slice.datasource_type) == self.type, ), ) # placeholder for a relationship to a derivative of BaseColumn
Example #8
Source File: schedules.py From incubator-superset with Apache License 2.0 | 5 votes |
def user(self) -> RelationshipProperty: return relationship( security_manager.user_model, backref=self.__tablename__, foreign_keys=[self.user_id], )
Example #9
Source File: alchemy.py From flask-rest-jsonapi with MIT License | 5 votes |
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'])
Example #10
Source File: helpers.py From planespotter with MIT License | 5 votes |
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 #11
Source File: sanity.py From cum with Apache License 2.0 | 5 votes |
def test_columns(self, table): """Tests the columns in database table. If a column exists in the table, check that the column has correct datatype. If the column doesn't exist, add a MissingColumn object to the error list. """ columns = self.inspection_engine.get_columns(table) column_names = [c["name"] for c in columns] # Search for correct class from models for the mapper. mapper = None for name, class_ in self.model_tables: if class_.__tablename__ == table: mapper = inspect(class_) break if not mapper: return for column_property in mapper.attrs: if isinstance(column_property, RelationshipProperty): # TODO: Add RelationshipProperty sanity checking. pass else: for column in column_property.columns: if column.key in column_names: self.test_datatype(table, column) self.test_nullable(table, column) else: self.errors.append(MissingColumn(table, column.key, parent=self))
Example #12
Source File: inspection.py From sqlalchemy-mixins with MIT License | 5 votes |
def relations(cls): """Return a `list` of relationship names or the given model """ return [c.key for c in cls.__mapper__.iterate_properties if isinstance(c, RelationshipProperty)]
Example #13
Source File: query.py From py-mongosql with BSD 2-Clause "Simplified" License | 5 votes |
def as_relation_of(self, mongoquery: 'MongoQuery', relationship: RelationshipProperty) -> 'MongoQuery': """ Handle the query as a sub-query handling a relationship This is used by the MongoJoin handler to build queries to related models. :param mongoquery: The parent query :param relationship: The relationship """ return self.as_relation(mongoquery._join_path + (relationship,))
Example #14
Source File: bag.py From py-mongosql with BSD 2-Clause "Simplified" License | 5 votes |
def _is_relationship_array(rel: RelationshipProperty) -> bool: """ Is the relationship an array relationship? """ return rel.property.uselist
Example #15
Source File: bag.py From py-mongosql with BSD 2-Clause "Simplified" License | 5 votes |
def get_relationship(self, col_name: str) -> RelationshipProperty: return self._rel_bag[self.get_relationship_name(col_name)]
Example #16
Source File: bag.py From py-mongosql with BSD 2-Clause "Simplified" License | 5 votes |
def __getitem__(self, name: str) -> RelationshipProperty: return self._relations[name]
Example #17
Source File: bag.py From py-mongosql with BSD 2-Clause "Simplified" License | 5 votes |
def __iter__(self) -> Iterable[Tuple[str, RelationshipProperty]]: """ Get relationships """ return iter(self._relations.items())
Example #18
Source File: bag.py From py-mongosql with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, relationships: Mapping[str, RelationshipProperty]): """ Init relationships :param relationships: Model relationships """ super(RelationshipsBag, self).__init__() self._relations = relationships self._rel_names = frozenset(self._relations.keys()) self._array_rel_names = frozenset(name for name, rel in self._relations.items() if _is_relationship_array(rel))
Example #19
Source File: management_database.py From postgraas_server with Apache License 2.0 | 4 votes |
def is_sane_database(Base, session): # pragma: no cover """ from: http://stackoverflow.com/questions/30428639/check-database-schema-matches-sqlalchemy-models-on-application-startup Check whether the current database matches the models declared in model base. Currently we check that all tables exist with all columns. What is not checked * Column types are not verified * Relationships are not verified at all (TODO) :param Base: Declarative Base for SQLAlchemy models to check :param session: SQLAlchemy session bound to an engine :return: True if all declared models have corresponding tables and columns. """ engine = session.get_bind() iengine = inspect(engine) errors = False tables = iengine.get_table_names() # Go through all SQLAlchemy models for name, klass in Base._decl_class_registry.items(): if isinstance(klass, _ModuleMarker): # Not a model continue table = klass.__tablename__ if table in tables: # Check all columns are found # Looks like [{'default': "nextval('sanity_check_test_id_seq'::regclass)", 'autoincrement': True, 'nullable': False, 'type': INTEGER(), 'name': 'id'}] columns = [c["name"] for c in iengine.get_columns(table)] mapper = inspect(klass) for column_prop in mapper.attrs: if isinstance(column_prop, RelationshipProperty): # TODO: Add sanity checks for relations pass else: for column in column_prop.columns: # Assume normal flat column if column.key not in columns: logger.error( "Model %s declares column %s which does not exist in database %s", klass, column.key, engine ) errors = True else: logger.error( "Model %s declares table %s which does not exist in database %s", klass, table, engine ) errors = True return not errors