Python classes are mapped to the database using the mapper() function.
Return a new Mapper object.
Parameters: |
|
---|
A basic mapping of a class will simply make the columns of the database table or selectable available as attributes on the class. Mapper properties allow you to customize and add additional properties to your classes, for example making the results one-to-many join available as a Python list of related objects.
Mapper properties are most commonly included in the mapper() call:
mapper(Parent, properties={
'children': relationship(Children)
}
Create a back reference with explicit arguments, which are the same arguments one can send to relationship().
Used with the backref keyword argument to relationship() in place of a string argument.
Provide a column-level property for use with a Mapper.
Column-based properties can normally be applied to the mapper’s properties dictionary using the schema.Column element directly. Use this function when the given column is not directly present within the mapper’s selectable; examples include SQL expressions, functions, and scalar SELECT queries.
Columns that aren’t present in the mapper’s selectable won’t be persisted by the mapper and are effectively “read-only” attributes.
- *cols
- list of Column objects to be mapped.
- comparator_factory
- a class which extends sqlalchemy.orm.properties.ColumnProperty.Comparator which provides custom SQL clause generation for comparison operations.
- group
- a group name for this property when marked as deferred.
- deferred
- when True, the column property is “deferred”, meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also deferred().
- doc
- optional string that will be applied as the doc on the class-bound descriptor.
- extension
- an AttributeExtension instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. These listeners will receive append and set events before the operation proceeds, and may be used to halt (via exception throw) or change the value used in the operation.
Provide query semantics for an unmanaged attribute.
Allows a regular Python @property (descriptor) to be used in Queries and SQL constructs like a managed attribute. comparable_property wraps a descriptor with a proxy that directs operator overrides such as == (__eq__) to the supplied comparator but proxies everything else through to the original descriptor:
class MyClass(object):
@property
def myprop(self):
return 'foo'
class MyComparator(sqlalchemy.orm.interfaces.PropComparator):
def __eq__(self, other):
....
mapper(MyClass, mytable, properties=dict(
'myprop': comparable_property(MyComparator)))
Used with the properties dictionary sent to mapper().
Optional when used in a properties={} declaration. The Python descriptor or property to layer comparison behavior on top of.
The like-named descriptor will be automatically retreived from the mapped class if left blank in a properties declaration.
Return a composite column-based property for use with a Mapper.
This is very much like a column-based property except the given class is used to represent “composite” values composed of one or more columns.
The class must implement a constructor with positional arguments matching the order of columns supplied here, as well as a __composite_values__() method which returns values in the same order.
A simple example is representing separate two columns in a table as a single, first-class “Point” object:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __composite_values__(self):
return self.x, self.y
def __eq__(self, other):
return other is not None and self.x == other.x and self.y == other.y
# and then in the mapping:
... composite(Point, mytable.c.x, mytable.c.y) ...
The composite object may have its attributes populated based on the names of the mapped columns. To override the way internal state is set, additionally implement __set_composite_values__:
class Point(object):
def __init__(self, x, y):
self.some_x = x
self.some_y = y
def __composite_values__(self):
return self.some_x, self.some_y
def __set_composite_values__(self, x, y):
self.some_x = x
self.some_y = y
def __eq__(self, other):
return other is not None and self.some_x == other.x and self.some_y == other.y
Arguments are:
Return a DeferredColumnProperty, which indicates this object attributes should only be loaded from its corresponding table column when first accessed.
Used with the properties dictionary sent to mapper().
Construct a dynamically-loading mapper property.
This property is similar to relationship(), except read operations return an active Query object which reads from the database when accessed. Items may be appended to the attribute via append(), or removed via remove(); changes will be persisted to the database during a Sesion.flush(). However, no other Python list or collection mutation operations are available.
A subset of arguments available to relationship() are available here.
Parameters: |
|
---|
Provide a relationship of a primary Mapper to a secondary Mapper.
Note
This function is known as relation() in all versions of SQLAlchemy prior to version 0.6beta2, including the 0.5 and 0.4 series. relationship() is only available starting with SQLAlchemy 0.6beta2. The relation() name will remain available for the foreseeable future in order to enable cross-compatibility.
This corresponds to a parent-child or associative table relationship. The constructed class is an instance of RelationshipProperty.
A typical relationship():
mapper(Parent, properties={
'children': relationship(Children)
})
Parameters: |
|
---|
Set up name as a synonym to another mapped property.
Used with the properties dictionary sent to mapper().
Any existing attributes on the class which map the key name sent to the properties dictionary will be used by the synonym to provide instance-attribute behavior (that is, any Python property object, provided by the property builtin or providing a __get__(), __set__() and __del__() method). If no name exists for the key, the synonym() creates a default getter/setter object automatically and applies it to the class.
name refers to the name of the existing mapped property, which can be any other MapperProperty including column-based properties and relationships.
If map_column is True, an additional ColumnProperty is created on the mapper automatically, using the synonym’s name as the keyname of the property, and the keyname of this synonym() as the name of the column to map. For example, if a table has a column named status:
class MyClass(object):
def _get_status(self):
return self._status
def _set_status(self, value):
self._status = value
status = property(_get_status, _set_status)
mapper(MyClass, sometable, properties={
"status":synonym("_status", map_column=True)
})
The column named status will be mapped to the attribute named _status, and the status attribute on MyClass will be used to proxy access to the column-based attribute.
Decorate a method as the ‘reconstructor’ hook.
Designates a method as the “reconstructor”, an __init__-like method that will be called by the ORM after the instance has been loaded from the database or otherwise reconstituted.
The reconstructor will be invoked with no arguments. Scalar (non-collection) database-mapped attributes of the instance will be available for use within the function. Eagerly-loaded collections are generally not yet available and will usually only contain the first element. ORM state changes made to objects at this stage will not be recorded for the next flush() operation, so the activity within a reconstructor should be conservative.
Decorate a method as a ‘validator’ for one or more named properties.
Designates a method as a validator, a method which receives the name of the attribute as well as a value to be assigned, or in the case of a collection to be added to the collection. The function can then raise validation exceptions to halt the process from continuing, or can modify or replace the value before proceeding. The function should otherwise return the given value.
Given an object, return the primary Mapper associated with the object instance.
Raises UnmappedInstanceError if no mapping is configured.
Given a class, return the primary Mapper associated with the key.
Raises UnmappedClassError if no mapping is configured.
Compile all mappers that have been defined.
This is equivalent to calling compile() on any individual mapper.
Remove all mappers that have been created thus far.
The mapped classes will return to their initial “unmapped” state and can be re-mapped with new mappers.
Delete the value of an attribute, firing history events.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to establish attribute state as understood by SQLAlchemy.
Get the value of an attribute, firing any callables required.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to make usage of attribute state as understood by SQLAlchemy.
Return a History record for the given object and attribute key.
obj is an instrumented object instance. An InstanceState is accepted directly for backwards compatibility but this usage is deprecated.
Initialize a collection attribute and return the collection adapter.
This function is used to provide direct access to collection internals for a previously unloaded attribute. e.g.:
collection_adapter = init_collection(someobject, 'elements')
for elem in values:
collection_adapter.append_without_event(elem)
For an easier way to do the above, see set_committed_value().
obj is an instrumented object instance. An InstanceState is accepted directly for backwards compatibility but this usage is deprecated.
Return True if the given attribute on the given instance is instrumented by the attributes package.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required.
Set the value of an attribute, firing history events.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to establish attribute state as understood by SQLAlchemy.
Set the value of an attribute with no history events.
Cancels any previous history present. The value should be a scalar value for scalar-holding attributes, or an iterable for any collection-holding attribute.
This is the same underlying method used when a lazy loader fires off and loads additional data from the database. In particular, this method can be used by application code which has loaded additional attributes or collections through separate queries, which can then be attached to an instance as though it were part of its original loaded state.
Define the correlation of class attributes to database table columns.
Instances of this class should be constructed via the mapper() function.
Construct a new mapper.
Add an individual MapperProperty to this mapper.
If the mapper has not been compiled yet, just adds the property to the initial properties dictionary sent to the constructor. If this Mapper has already been compiled, then the given MapperProperty is compiled immediately.
Iterate each element and its mapper in an object graph, for all relationships that meet the given cascade rule.
the return value are object instances; this provides a strong reference so that they don’t fall out of scope immediately.
Compile this mapper and all other non-compiled mappers.
This method checks the local compiled status as well as for any new mappers that have been defined, and is safe to call repeatedly.
Return the identity key for the given instance, based on its primary key attributes.
This value is typically also found on the instance state under the attribute name key.
Return an identity-map key for use in storing/retrieving an item from an identity map.
Return an identity-map key for use in storing/retrieving an item from the identity map.
Iterate through the collection including this mapper and all descendant mappers.
This includes not just the immediately inheriting mappers but all their inheriting mappers as well.
To iterate through an entire hierarchy, use mapper.base_mapper.polymorphic_iterator().