Key ORM constructs, not otherwise covered in other sections, are listed here.
Provide an inspection interface corresponding to a particular attribute on a particular mapped object.
The AttributeState object is accessed via the InstanceState.attrs collection of a particular InstanceState:
from sqlalchemy import inspect
insp = inspect(some_mapped_object)
attr_state = insp.attrs.some_attribute
Inherited-members : | |
---|---|
Return the current pre-flush change history for this attribute, via the History interface.
This method will not emit loader callables if the value of the attribute is unloaded.
See also
AttributeState.load_history() - retrieve history using loader callables if the value is not locally present.
attributes.get_history() - underlying function
Return the current pre-flush change history for this attribute, via the History interface.
This method will emit loader callables if the value of the attribute is unloaded.
New in version 0.9.0.
The current value of this attribute as loaded from the database.
If the value has not been loaded, or is otherwise not present in the object’s dictionary, returns NO_VALUE.
Return the value of this attribute.
This operation is equivalent to accessing the object’s attribute directly or via getattr(), and will fire off any pending loader callables if needed.
Bases: __builtin__.dict
tracks state information at the class level.
Inherited-members : | |
---|---|
Dissasociate this manager from its class.
TODO
Mark this instance as the manager for its class.
x.__init__(...) initializes x; see help(type(x)) for signature
Return a (instance) -> InstanceState callable.
“state getter” callables should raise either KeyError or AttributeError if no InstanceState could be found for the instance.
remove all instrumentation established by this ClassManager.
Bases: sqlalchemy.orm.interfaces.StrategizedProperty
Describes an object attribute that corresponds to a table column.
Public constructor is the orm.column_property() function.
Inherited-members : | |
---|---|
Bases: sqlalchemy.orm.interfaces.PropComparator
Produce boolean, comparison, and other operators for ColumnProperty attributes.
See the documentation for PropComparator for a brief overview.
See also:
Construct a new ColumnProperty object.
This constructor is mirrored as a public API function; see column_property() for a full usage and argument description.
Return the primary column or expression for this ColumnProperty.
Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty
Defines a “composite” mapped attribute, representing a collection of columns as one attribute.
CompositeProperty is constructed using the composite() function.
See also
Bases: sqlalchemy.orm.interfaces.PropComparator
Produce boolean, comparison, and other operators for CompositeProperty attributes.
See the example in Redefining Comparison Operations for Composites for an overview of usage , as well as the documentation for PropComparator.
See also:
Construct a new CompositeProperty object.
This constructor is mirrored as a public API function; see composite() for a full usage and argument description.
Initialization which occurs after the CompositeProperty has been associated with its parent mapper.
Provided for userland code that uses attributes.get_history().
A token propagated throughout the course of a chain of attribute events.
Serves as an indicator of the source of the event and also provides a means of controlling propagation across a chain of attribute operations.
The Event object is sent as the initiator argument when dealing with the AttributeEvents.append(), AttributeEvents.set(), and AttributeEvents.remove() events.
The Event object is currently interpreted by the backref event handlers, and is used to control the propagation of operations across two mutually-dependent attributes.
New in version 0.9.0.
The AttributeImpl which is the current event initiator.
The symbol OP_APPEND, OP_REMOVE or OP_REPLACE, indicating the source operation.
A base class applied to all ORM objects that can be returned by the inspect() function.
The attributes defined here allow the usage of simple boolean checks to test basic facts about the object returned.
While the boolean checks here are basically the same as using the Python isinstance() function, the flags here can be used without the need to import all of these classes, and also such that the SQLAlchemy class system can change while leaving the flags here intact for forwards-compatibility.
The extension type, if any. Defaults to interfaces.NOT_EXTENSION
New in version 0.8.0.
True if this object is an instance of AliasedClass.
True if this object is a Python descriptor.
This can refer to one of many types. Usually a QueryableAttribute which handles attributes events on behalf of a MapperProperty. But can also be an extension type such as AssociationProxy or hybrid_property. The _InspectionAttr.extension_type will refer to a constant identifying the specific subtype.
See also
True if this object is an instance of ClauseElement.
True if this object is an instance of InstanceState.
True if this object is an instance of MapperProperty.
Return True if this object is an instance of Selectable.
Bases: sqlalchemy.orm.base._InspectionAttr
tracks state information at the instance level.
__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable).
Return a namespace representing each attribute on the mapped object, including its current value and history.
The returned object is an instance of AttributeState.
Return true if the object is detached.
Return the set of keys which are ‘expired’ to be loaded by the manager’s deferred scalar loader, assuming no pending changes.
see also the unmodified collection which is intersected against this set when a refresh operation occurs.
Return True if this object has an identity key.
This should always have the same value as the expression state.persistent or state.detached.
Return the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to Query.get().
Returns None if the object has no primary key identity.
Note
An object which is transient or pending does not have a mapped identity until it is flushed, even if its attributes include primary key values.
Return the identity key for the mapped object.
This is the key used to locate the object within the Session.identity_map mapping. It contains the identity as returned by identity within it.
Return the mapped object represented by this InstanceState.
Return true if the object is pending.
Return true if the object is persistent.
Return true if the object is transient.
Return the set of keys which do not have a loaded value.
This includes expired attributes and any other attribute that was never populated or modified.
Return the set of keys which have no uncommitted changes
Return self.unmodified.intersection(keys).
Bases: sqlalchemy.orm.attributes.QueryableAttribute
Class bound instrumented attribute which adds basic descriptor methods.
See QueryableAttribute for a description of most features.
Undoc-members : |
---|
Indicates the many-to-one direction for a relationship().
This symbol is typically used by the internals but may be exposed within certain API features.
Indicates the many-to-many direction for a relationship().
This symbol is typically used by the internals but may be exposed within certain API features.
Bases: sqlalchemy.orm.base._MappedAttribute, sqlalchemy.orm.base._InspectionAttr
Manage the relationship of a Mapper to a single class attribute, as well as that attribute as it appears on individual instances of the class, including attribute instrumentation, attribute access, loading behavior, and dependency calculations.
The most common occurrences of MapperProperty are the mapped Column, which is represented in a mapping as an instance of ColumnProperty, and a reference to another class produced by relationship(), represented in the mapping as an instance of RelationshipProperty.
The set of ‘cascade’ attribute names.
This collection is checked before the ‘cascade_iterator’ method is called.
Iterate through instances related to the given instance for a particular ‘cascade’, starting with this MapperProperty.
Return an iterator3-tuples (instance, mapper, state).
Note that the ‘cascade’ collection on this MapperProperty is checked first for the given type before cascade_iterator is called.
See PropertyLoader for the related instance implementation.
Return the class-bound descriptor corresponding to this MapperProperty.
This is basically a getattr() call:
return getattr(self.parent.class_, self.key)
I.e. if this MapperProperty were named addresses, and the class to which it is mapped is User, this sequence is possible:
>>> from sqlalchemy import inspect
>>> mapper = inspect(User)
>>> addresses_property = mapper.attrs.addresses
>>> addresses_property.class_attribute is User.addresses
True
>>> User.addresses.property is addresses_property
True
Return a compare operation for the columns represented by this MapperProperty to the given value, which may be a column value or an instance. ‘operator’ is an operator from the operators module, or from sql.Comparator.
By default uses the PropComparator attached to this MapperProperty under the attribute name “comparator”.
Return a 3-tuple consisting of three row processing functions.
Perform subclass-specific initialization post-mapper-creation steps.
This is a template method called by the MapperProperty object’s init() method.
Info dictionary associated with the object, allowing user-defined data to be associated with this MapperProperty.
The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the column_property(), relationship(), or composite() functions.
New in version 0.8: Added support for .info to all MapperProperty subclasses.
Called after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps.
Return True if this MapperProperty‘s mapper is the primary mapper for its class.
This flag is used to indicate that the MapperProperty can define attribute instrumentation for the class at the class level (as opposed to the individual instance level).
Merge the attribute represented by this MapperProperty from source to destination object
Perform instrumentation adjustments that need to occur after init() has completed.
Called by Query for the purposes of constructing a SQL statement.
Each MapperProperty associated with the target mapper processes the statement referenced by the query context, adding columns and/or criterion as appropriate.
Symbol indicating an _InspectionAttr that’s not part of sqlalchemy.ext.
Is assigned to the _InspectionAttr.extension_type attibute.
Indicates the one-to-many direction for a relationship().
This symbol is typically used by the internals but may be exposed within certain API features.
Bases: sqlalchemy.sql.operators.ColumnOperators
Defines boolean, comparison, and other operators for MapperProperty objects.
SQLAlchemy allows for operators to be redefined at both the Core and ORM level. PropComparator is the base class of operator redefinition for ORM-level operations, including those of ColumnProperty, RelationshipProperty, and CompositeProperty.
Note
With the advent of Hybrid properties introduced in SQLAlchemy 0.7, as well as Core-level operator redefinition in SQLAlchemy 0.8, the use case for user-defined PropComparator instances is extremely rare. See Hybrid Attributes as well as Redefining and Creating New Operators.
User-defined subclasses of PropComparator may be created. The built-in Python comparison and math operator methods, such as operators.ColumnOperators.__eq__(), operators.ColumnOperators.__lt__(), and operators.ColumnOperators.__add__(), can be overridden to provide new operator behavior. The custom PropComparator is passed to the MapperProperty instance via the comparator_factory argument. In each case, the appropriate subclass of PropComparator should be used:
# definition of custom PropComparator subclasses
from sqlalchemy.orm.properties import \
ColumnProperty,\
CompositeProperty,\
RelationshipProperty
class MyColumnComparator(ColumnProperty.Comparator):
def __eq__(self, other):
return self.__clause_element__() == other
class MyRelationshipComparator(RelationshipProperty.Comparator):
def any(self, expression):
"define the 'any' operation"
# ...
class MyCompositeComparator(CompositeProperty.Comparator):
def __gt__(self, other):
"redefine the 'greater than' operation"
return sql.and_(*[a>b for a, b in
zip(self.__clause_element__().clauses,
other.__composite_values__())])
# application of custom PropComparator subclasses
from sqlalchemy.orm import column_property, relationship, composite
from sqlalchemy import Column, String
class SomeMappedClass(Base):
some_column = column_property(Column("some_column", String),
comparator_factory=MyColumnComparator)
some_relationship = relationship(SomeOtherClass,
comparator_factory=MyRelationshipComparator)
some_composite = composite(
Column("a", String), Column("b", String),
comparator_factory=MyCompositeComparator
)
Note that for column-level operator redefinition, it’s usually simpler to define the operators at the Core level, using the TypeEngine.comparator_factory attribute. See Redefining and Creating New Operators for more detail.
See also:
RelationshipProperty.Comparator
Redefining and Creating New Operators
Inherited-members : | |
---|---|
Return a copy of this PropComparator which will use the given AliasedInsp to produce corresponding expressions.
Produce a callable that adapts column expressions to suit an aliased version of this comparator.
Return true if this collection contains any member that meets the given criterion.
The usual implementation of any() is RelationshipProperty.Comparator.any().
Parameters: |
---|
Return true if this element references a member which meets the given criterion.
The usual implementation of has() is RelationshipProperty.Comparator.has().
Parameters: |
---|
Redefine this object in terms of a polymorphic subclass.
Returns a new PropComparator from which further criterion can be evaluated.
e.g.:
query.join(Company.employees.of_type(Engineer)).\
filter(Engineer.name=='foo')
Parameters: | class_¶ – a class or mapper indicating that criterion will be against this specific subclass. |
---|
Bases: sqlalchemy.orm.interfaces.StrategizedProperty
Describes an object property that holds a single item or list of items that correspond to a related database table.
Public constructor is the orm.relationship() function.
See also:
Inherited-members : | |
---|---|
Bases: sqlalchemy.orm.interfaces.PropComparator
Produce boolean, comparison, and other operators for RelationshipProperty attributes.
See the documentation for PropComparator for a brief overview of ORM level operator definition.
See also:
Redefining and Creating New Operators
Implement the == operator.
In a many-to-one context, such as:
MyClass.some_prop == <some object>
this will typically produce a clause such as:
mytable.related_id == <some id>
Where <some id> is the primary key of the given object.
The == operator provides partial functionality for non- many-to-one comparisons:
Construction of RelationshipProperty.Comparator is internal to the ORM’s attribute mechanics.
Implement the != operator.
In a many-to-one context, such as:
MyClass.some_prop != <some object>
This will typically produce a clause such as:
mytable.related_id != <some id>
Where <some id> is the primary key of the given object.
The != operator provides partial functionality for non- many-to-one comparisons:
Produce an expression that tests a collection against particular criterion, using EXISTS.
An expression like:
session.query(MyClass).filter(
MyClass.somereference.any(SomeRelated.x==2)
)
Will produce a query like:
SELECT * FROM my_table WHERE
EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id
AND related.x=2)
Because any() uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join.
any() is particularly useful for testing for empty collections:
session.query(MyClass).filter(
~MyClass.somereference.any()
)
will produce:
SELECT * FROM my_table WHERE
NOT EXISTS (SELECT 1 FROM related WHERE
related.my_id=my_table.id)
any() is only valid for collections, i.e. a relationship() that has uselist=True. For scalar references, use has().
Return a simple expression that tests a collection for containment of a particular item.
contains() is only valid for a collection, i.e. a relationship() that implements one-to-many or many-to-many with uselist=True.
When used in a simple one-to-many context, an expression like:
MyClass.contains(other)
Produces a clause like:
mytable.id == <some id>
Where <some id> is the value of the foreign key attribute on other which refers to the primary key of its parent object. From this it follows that contains() is very useful when used with simple one-to-many operations.
For many-to-many operations, the behavior of contains() has more caveats. The association table will be rendered in the statement, producing an “implicit” join, that is, includes multiple tables in the FROM clause which are equated in the WHERE clause:
query(MyClass).filter(MyClass.contains(other))
Produces a query like:
SELECT * FROM my_table, my_association_table AS
my_association_table_1 WHERE
my_table.id = my_association_table_1.parent_id
AND my_association_table_1.child_id = <some id>
Where <some id> would be the primary key of other. From the above, it is clear that contains() will not work with many-to-many collections when used in queries that move beyond simple AND conjunctions, such as multiple contains() expressions joined by OR. In such cases subqueries or explicit “outer joins” will need to be used instead. See any() for a less-performant alternative using EXISTS, or refer to Query.outerjoin() as well as Querying with Joins for more details on constructing outer joins.
Produce an expression that tests a scalar reference against particular criterion, using EXISTS.
An expression like:
session.query(MyClass).filter(
MyClass.somereference.has(SomeRelated.x==2)
)
Will produce a query like:
SELECT * FROM my_table WHERE
EXISTS (SELECT 1 FROM related WHERE
related.id==my_table.related_id AND related.x=2)
Because has() uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join.
has() is only valid for scalar references, i.e. a relationship() that has uselist=False. For collection references, use any().
Produce an IN clause - this is not implemented for relationship()-based attributes at this time.
The target Mapper referred to by this RelationshipProperty.Comparator.
This is the “target” or “remote” side of the relationship().
Produce a construct that represents a particular ‘subtype’ of attribute for the parent class.
Currently this is usable in conjunction with Query.join() and Query.outerjoin().
Construct a new RelationshipProperty object.
This constructor is mirrored as a public API function; see relationship() for a full usage and argument description.
Return the current cascade setting for this RelationshipProperty.
Return the targeted Mapper for this RelationshipProperty.
This is a lazy-initializing static attribute.
Return the selectable linked to this RelationshipProperty object’s target Mapper.
Deprecated since version 0.7: Use .target
Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty
Inherited-members : | |
---|---|
Construct a new SynonymProperty object.
This constructor is mirrored as a public API function; see synonym() for a full usage and argument description.
Bases: sqlalchemy.orm.base._MappedAttribute, sqlalchemy.orm.base._InspectionAttr, sqlalchemy.orm.interfaces.PropComparator
Base class for descriptor objects that intercept attribute events on behalf of a MapperProperty object. The actual MapperProperty is accessible via the QueryableAttribute.property attribute.
Implement the == operator.
In a column context, produces the clause a = b. If the target is None, produces a IS NULL.
Implement the <= operator.
In a column context, produces the clause a <= b.
Implement the < operator.
In a column context, produces the clause a < b.
Implement the != operator.
In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.
Produce a callable that adapts column expressions to suit an aliased version of this comparator.
Return true if this collection contains any member that meets the given criterion.
The usual implementation of any() is RelationshipProperty.Comparator.any().
Parameters: |
---|
Produce a asc() clause against the parent object.
Produce a between() clause against the parent object, given the lower and upper range.
Produce a collate() clause against the parent object, given the collation string.
Implement the ‘concat’ operator.
In a column context, produces the clause a || b, or uses the concat() operator on MySQL.
Implement the ‘contains’ operator.
In a column context, produces the clause LIKE '%<other>%'
Produce a desc() clause against the parent object.
Produce a distinct() clause against the parent object.
Implement the ‘endswith’ operator.
In a column context, produces the clause LIKE '%<other>'
Return true if this element references a member which meets the given criterion.
The usual implementation of has() is RelationshipProperty.Comparator.has().
Parameters: |
---|
Implement the ilike operator.
In a column context, produces the clause a ILIKE other.
E.g.:
select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters: |
---|
See also
Implement the in operator.
In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.
Return the ‘info’ dictionary for the underlying SQL element.
The behavior here is as follows:
New in version 0.8.0.
Implement the IS operator.
Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.
New in version 0.7.9.
See also
Implement the IS NOT operator.
Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.
New in version 0.7.9.
See also
Implement the like operator.
In a column context, produces the clause a LIKE other.
E.g.:
select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters: |
---|
See also
Implements the ‘match’ operator.
In a column context, this produces a MATCH clause, i.e. MATCH '<other>'. The allowed contents of other are database backend specific.
implement the NOT ILIKE operator.
This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).
New in version 0.8.
See also
implement the NOT IN operator.
This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).
New in version 0.8.
See also
implement the NOT LIKE operator.
This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).
New in version 0.8.
See also
Produce a nullsfirst() clause against the parent object.
Produce a nullslast() clause against the parent object.
produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in somecolumn.
Parameters: |
|
---|
Return an inspection instance representing the parent.
This will be either an instance of Mapper or AliasedInsp, depending upon the nature of the parent entity which this attribute is associated with.
Return the MapperProperty associated with this QueryableAttribute.
Return values here will commonly be instances of ColumnProperty or RelationshipProperty.
Implement the startwith operator.
In a column context, produces the clause LIKE '<other>%'
Filter the given list of InstanceStates to those relevant to the given DependencyProcessor.
mark processed objects as clean / deleted after a successful flush().
this method is called within the flush() method after the execute() method has succeeded and the transaction has been committed.
facade to attributes.get_state_history(), including caching of results.
return true if the given state is marked as deleted within this uowtransaction.
remove pending actions for a state from the uowtransaction.