Collection Configuration and Techniques

The relationship() function defines a linkage between two classes. When the linkage defines a one-to-many or many-to-many relationship, it’s represented as a Python collection when objects are loaded and manipulated. This section presents additional information about collection configuration and techniques.

Working with Large Collections

The default behavior of relationship() is to fully load the collection of items in, as according to the loading strategy of the relationship. Additionally, the Session by default only knows how to delete objects which are actually present within the session. When a parent instance is marked for deletion and flushed, the Session loads its full list of child items in so that they may either be deleted as well, or have their foreign key value set to null; this is to avoid constraint violations. For large collections of child items, there are several strategies to bypass full loading of child items both at load time as well as deletion time.

Dynamic Relationship Loaders

Note

This is a legacy feature. Using the with_parent() filter in conjunction with select() is the 2.0 style method of use. For relationships that shouldn’t load, set relationship.lazy to noload.

A relationship() which corresponds to a large collection can be configured so that it returns a legacy Query object when accessed, which allows filtering of the relationship on criteria. The class is a special class AppenderQuery returned in place of a collection when accessed. Filtering criterion may be applied as well as limits and offsets, either explicitly or via array slices:

  1. class User(Base):
  2. __tablename__ = 'user'
  3. posts = relationship(Post, lazy="dynamic")
  4. jack = session.query(User).get(id)
  5. # filter Jack's blog posts
  6. posts = jack.posts.filter(Post.headline=='this is a post')
  7. # apply array slices
  8. posts = jack.posts[5:20]

The dynamic relationship supports limited write operations, via the AppenderQuery.append() and AppenderQuery.remove() methods:

  1. oldpost = jack.posts.filter(Post.headline=='old post').one()
  2. jack.posts.remove(oldpost)
  3. jack.posts.append(Post('new post'))

Since the read side of the dynamic relationship always queries the database, changes to the underlying collection will not be visible until the data has been flushed. However, as long as “autoflush” is enabled on the Session in use, this will occur automatically each time the collection is about to emit a query.

To place a dynamic relationship on a backref, use the backref() function in conjunction with lazy='dynamic':

  1. class Post(Base):
  2. __table__ = posts_table
  3. user = relationship(User,
  4. backref=backref('posts', lazy='dynamic')
  5. )

Note that eager/lazy loading options cannot be used in conjunction dynamic relationships at this time.

Object NameDescription

AppenderQuery

A dynamic query that supports basic collection storage operations.

class sqlalchemy.orm.``AppenderQuery(attr, state)

A dynamic query that supports basic collection storage operations.

Class signature

class sqlalchemy.orm.AppenderQuery (sqlalchemy.orm.dynamic.AppenderMixin, sqlalchemy.orm.Query)

Note

The dynamic_loader() function is essentially the same as relationship() with the lazy='dynamic' argument specified.

Warning

The “dynamic” loader applies to collections only. It is not valid to use “dynamic” loaders with many-to-one, one-to-one, or uselist=False relationships. Newer versions of SQLAlchemy emit warnings or exceptions in these cases.

Setting Noload, RaiseLoad

A “noload” relationship never loads from the database, even when accessed. It is configured using lazy='noload':

  1. class MyClass(Base):
  2. __tablename__ = 'some_table'
  3. children = relationship(MyOtherClass, lazy='noload')

Above, the children collection is fully writeable, and changes to it will be persisted to the database as well as locally available for reading at the time they are added. However when instances of MyClass are freshly loaded from the database, the children collection stays empty. The noload strategy is also available on a query option basis using the noload() loader option.

Alternatively, a “raise”-loaded relationship will raise an InvalidRequestError where the attribute would normally emit a lazy load:

  1. class MyClass(Base):
  2. __tablename__ = 'some_table'
  3. children = relationship(MyOtherClass, lazy='raise')

Above, attribute access on the children collection will raise an exception if it was not previously eagerloaded. This includes read access but for collections will also affect write access, as collections can’t be mutated without first loading them. The rationale for this is to ensure that an application is not emitting any unexpected lazy loads within a certain context. Rather than having to read through SQL logs to determine that all necessary attributes were eager loaded, the “raise” strategy will cause unloaded attributes to raise immediately if accessed. The raise strategy is also available on a query option basis using the raiseload() loader option.

New in version 1.1: added the “raise” loader strategy.

See also

Preventing unwanted lazy loads using raiseload

Using Passive Deletes

See Using foreign key ON DELETE cascade with ORM relationships for this section.

Customizing Collection Access

Mapping a one-to-many or many-to-many relationship results in a collection of values accessible through an attribute on the parent instance. By default, this collection is a list:

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. parent_id = Column(Integer, primary_key=True)
  4. children = relationship(Child)
  5. parent = Parent()
  6. parent.children.append(Child())
  7. print(parent.children[0])

Collections are not limited to lists. Sets, mutable sequences and almost any other Python object that can act as a container can be used in place of the default list, by specifying the relationship.collection_class option on relationship():

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. parent_id = Column(Integer, primary_key=True)
  4. # use a set
  5. children = relationship(Child, collection_class=set)
  6. parent = Parent()
  7. child = Child()
  8. parent.children.add(child)
  9. assert child in parent.children

Dictionary Collections

A little extra detail is needed when using a dictionary as a collection. This because objects are always loaded from the database as lists, and a key-generation strategy must be available to populate the dictionary correctly. The attribute_mapped_collection() function is by far the most common way to achieve a simple dictionary collection. It produces a dictionary class that will apply a particular attribute of the mapped class as a key. Below we map an Item class containing a dictionary of Note items keyed to the Note.keyword attribute:

  1. from sqlalchemy import Column, Integer, String, ForeignKey
  2. from sqlalchemy.orm import relationship
  3. from sqlalchemy.orm.collections import attribute_mapped_collection
  4. from sqlalchemy.ext.declarative import declarative_base
  5. Base = declarative_base()
  6. class Item(Base):
  7. __tablename__ = 'item'
  8. id = Column(Integer, primary_key=True)
  9. notes = relationship("Note",
  10. collection_class=attribute_mapped_collection('keyword'),
  11. cascade="all, delete-orphan")
  12. class Note(Base):
  13. __tablename__ = 'note'
  14. id = Column(Integer, primary_key=True)
  15. item_id = Column(Integer, ForeignKey('item.id'), nullable=False)
  16. keyword = Column(String)
  17. text = Column(String)
  18. def __init__(self, keyword, text):
  19. self.keyword = keyword
  20. self.text = text

Item.notes is then a dictionary:

  1. >>> item = Item()
  2. >>> item.notes['a'] = Note('a', 'atext')
  3. >>> item.notes.items()
  4. {'a': <__main__.Note object at 0x2eaaf0>}

attribute_mapped_collection() will ensure that the .keyword attribute of each Note complies with the key in the dictionary. Such as, when assigning to Item.notes, the dictionary key we supply must match that of the actual Note object:

  1. item = Item()
  2. item.notes = {
  3. 'a': Note('a', 'atext'),
  4. 'b': Note('b', 'btext')
  5. }

The attribute which attribute_mapped_collection() uses as a key does not need to be mapped at all! Using a regular Python @property allows virtually any detail or combination of details about the object to be used as the key, as below when we establish it as a tuple of Note.keyword and the first ten letters of the Note.text field:

  1. class Item(Base):
  2. __tablename__ = 'item'
  3. id = Column(Integer, primary_key=True)
  4. notes = relationship("Note",
  5. collection_class=attribute_mapped_collection('note_key'),
  6. backref="item",
  7. cascade="all, delete-orphan")
  8. class Note(Base):
  9. __tablename__ = 'note'
  10. id = Column(Integer, primary_key=True)
  11. item_id = Column(Integer, ForeignKey('item.id'), nullable=False)
  12. keyword = Column(String)
  13. text = Column(String)
  14. @property
  15. def note_key(self):
  16. return (self.keyword, self.text[0:10])
  17. def __init__(self, keyword, text):
  18. self.keyword = keyword
  19. self.text = text

Above we added a Note.item backref. Assigning to this reverse relationship, the Note is added to the Item.notes dictionary and the key is generated for us automatically:

  1. >>> item = Item()
  2. >>> n1 = Note("a", "atext")
  3. >>> n1.item = item
  4. >>> item.notes
  5. {('a', 'atext'): <__main__.Note object at 0x2eaaf0>}

Other built-in dictionary types include column_mapped_collection(), which is almost like attribute_mapped_collection() except given the Column object directly:

  1. from sqlalchemy.orm.collections import column_mapped_collection
  2. class Item(Base):
  3. __tablename__ = 'item'
  4. id = Column(Integer, primary_key=True)
  5. notes = relationship("Note",
  6. collection_class=column_mapped_collection(Note.__table__.c.keyword),
  7. cascade="all, delete-orphan")

as well as mapped_collection() which is passed any callable function. Note that it’s usually easier to use attribute_mapped_collection() along with a @property as mentioned earlier:

  1. from sqlalchemy.orm.collections import mapped_collection
  2. class Item(Base):
  3. __tablename__ = 'item'
  4. id = Column(Integer, primary_key=True)
  5. notes = relationship("Note",
  6. collection_class=mapped_collection(lambda note: note.text[0:10]),
  7. cascade="all, delete-orphan")

Dictionary mappings are often combined with the “Association Proxy” extension to produce streamlined dictionary views. See Proxying to Dictionary Based Collections and Composite Association Proxies for examples.

Dealing with Key Mutations and back-populating for Dictionary collections

When using attribute_mapped_collection(), the “key” for the dictionary is taken from an attribute on the target object. Changes to this key are not tracked. This means that the key must be assigned towards when it is first used, and if the key changes, the collection will not be mutated. A typical example where this might be an issue is when relying upon backrefs to populate an attribute mapped collection. Given the following:

  1. class A(Base):
  2. __tablename__ = "a"
  3. id = Column(Integer, primary_key=True)
  4. bs = relationship(
  5. "B",
  6. collection_class=attribute_mapped_collection("data"),
  7. back_populates="a",
  8. )
  9. class B(Base):
  10. __tablename__ = "b"
  11. id = Column(Integer, primary_key=True)
  12. a_id = Column(ForeignKey("a.id"))
  13. data = Column(String)
  14. a = relationship("A", back_populates="bs")

Above, if we create a B() that refers to a specific A(), the back populates will then add the B() to the A.bs collection, however if the value of B.data is not set yet, the key will be None:

  1. >>> a1 = A()
  2. >>> b1 = B(a=a1)
  3. >>> a1.bs
  4. {None: <test3.B object at 0x7f7b1023ef70>}

Setting b1.data after the fact does not update the collection:

  1. >>> b1.data = 'the key'
  2. >>> a1.bs
  3. {None: <test3.B object at 0x7f7b1023ef70>}

This can also be seen if one attempts to set up B() in the constructor. The order of arguments changes the result:

  1. >>> B(a=a1, data='the key')
  2. <test3.B object at 0x7f7b10114280>
  3. >>> a1.bs
  4. {None: <test3.B object at 0x7f7b10114280>}

vs:

  1. >>> B(data='the key', a=a1)
  2. <test3.B object at 0x7f7b10114340>
  3. >>> a1.bs
  4. {'the key': <test3.B object at 0x7f7b10114340>}

If backrefs are being used in this way, ensure that attributes are populated in the correct order using an __init__ method.

An event handler such as the following may also be used to track changes in the collection as well:

  1. from sqlalchemy import event
  2. from sqlalchemy.orm import attributes
  3. @event.listens_for(B.data, "set")
  4. def set_item(obj, value, previous, initiator):
  5. if obj.a is not None:
  6. previous = None if previous == attributes.NO_VALUE else previous
  7. obj.a.bs[value] = obj
  8. obj.a.bs.pop(previous)
Object NameDescription

attribute_mapped_collection(attr_name)

A dictionary-based collection type with attribute-based keying.

column_mapped_collection(mapping_spec)

A dictionary-based collection type with column-based keying.

mapped_collection(keyfunc)

A dictionary-based collection type with arbitrary keying.

function sqlalchemy.orm.collections.``attribute_mapped_collection(attr_name)

A dictionary-based collection type with attribute-based keying.

Returns a MappedCollection factory with a keying based on the ‘attr_name’ attribute of entities in the collection, where attr_name is the string name of the attribute.

Warning

the key value must be assigned to its final value before it is accessed by the attribute mapped collection. Additionally, changes to the key attribute are not tracked automatically, which means the key in the dictionary is not automatically synchronized with the key value on the target object itself. See the section Dealing with Key Mutations and back-populating for Dictionary collections for an example.

function sqlalchemy.orm.collections.``column_mapped_collection(mapping_spec)

A dictionary-based collection type with column-based keying.

Returns a MappedCollection factory with a keying function generated from mapping_spec, which may be a Column or a sequence of Columns.

The key value must be immutable for the lifetime of the object. You can not, for example, map on foreign key values if those key values will change during the session, i.e. from None to a database-assigned integer after a session flush.

function sqlalchemy.orm.collections.``mapped_collection(keyfunc)

A dictionary-based collection type with arbitrary keying.

Returns a MappedCollection factory with a keying function generated from keyfunc, a callable that takes an entity and returns a key value.

The key value must be immutable for the lifetime of the object. You can not, for example, map on foreign key values if those key values will change during the session, i.e. from None to a database-assigned integer after a session flush.

Custom Collection Implementations

You can use your own types for collections as well. In simple cases, inheriting from list or set, adding custom behavior, is all that’s needed. In other cases, special decorators are needed to tell SQLAlchemy more detail about how the collection operates.

Do I need a custom collection implementation?

In most cases not at all! The most common use cases for a “custom” collection is one that validates or marshals incoming values into a new form, such as a string that becomes a class instance, or one which goes a step beyond and represents the data internally in some fashion, presenting a “view” of that data on the outside of a different form.

For the first use case, the validates() decorator is by far the simplest way to intercept incoming values in all cases for the purposes of validation and simple marshaling. See Simple Validators for an example of this.

For the second use case, the Association Proxy extension is a well-tested, widely used system that provides a read/write “view” of a collection in terms of some attribute present on the target object. As the target attribute can be a @property that returns virtually anything, a wide array of “alternative” views of a collection can be constructed with just a few functions. This approach leaves the underlying mapped collection unaffected and avoids the need to carefully tailor collection behavior on a method-by-method basis.

Customized collections are useful when the collection needs to have special behaviors upon access or mutation operations that can’t otherwise be modeled externally to the collection. They can of course be combined with the above two approaches.

Collections in SQLAlchemy are transparently instrumented. Instrumentation means that normal operations on the collection are tracked and result in changes being written to the database at flush time. Additionally, collection operations can fire events which indicate some secondary operation must take place. Examples of a secondary operation include saving the child item in the parent’s Session (i.e. the save-update cascade), as well as synchronizing the state of a bi-directional relationship (i.e. a backref()).

The collections package understands the basic interface of lists, sets and dicts and will automatically apply instrumentation to those built-in types and their subclasses. Object-derived types that implement a basic collection interface are detected and instrumented via duck-typing:

  1. class ListLike(object):
  2. def __init__(self):
  3. self.data = []
  4. def append(self, item):
  5. self.data.append(item)
  6. def remove(self, item):
  7. self.data.remove(item)
  8. def extend(self, items):
  9. self.data.extend(items)
  10. def __iter__(self):
  11. return iter(self.data)
  12. def foo(self):
  13. return 'foo'

append, remove, and extend are known list-like methods, and will be instrumented automatically. __iter__ is not a mutator method and won’t be instrumented, and foo won’t be either.

Duck-typing (i.e. guesswork) isn’t rock-solid, of course, so you can be explicit about the interface you are implementing by providing an __emulates__ class attribute:

  1. class SetLike(object):
  2. __emulates__ = set
  3. def __init__(self):
  4. self.data = set()
  5. def append(self, item):
  6. self.data.add(item)
  7. def remove(self, item):
  8. self.data.remove(item)
  9. def __iter__(self):
  10. return iter(self.data)

This class looks list-like because of append, but __emulates__ forces it to set-like. remove is known to be part of the set interface and will be instrumented.

But this class won’t work quite yet: a little glue is needed to adapt it for use by SQLAlchemy. The ORM needs to know which methods to use to append, remove and iterate over members of the collection. When using a type like list or set, the appropriate methods are well-known and used automatically when present. This set-like class does not provide the expected add method, so we must supply an explicit mapping for the ORM via a decorator.

Annotating Custom Collections via Decorators

Decorators can be used to tag the individual methods the ORM needs to manage collections. Use them when your class doesn’t quite meet the regular interface for its container type, or when you otherwise would like to use a different method to get the job done.

  1. from sqlalchemy.orm.collections import collection
  2. class SetLike(object):
  3. __emulates__ = set
  4. def __init__(self):
  5. self.data = set()
  6. @collection.appender
  7. def append(self, item):
  8. self.data.add(item)
  9. def remove(self, item):
  10. self.data.remove(item)
  11. def __iter__(self):
  12. return iter(self.data)

And that’s all that’s needed to complete the example. SQLAlchemy will add instances via the append method. remove and __iter__ are the default methods for sets and will be used for removing and iteration. Default methods can be changed as well:

  1. from sqlalchemy.orm.collections import collection
  2. class MyList(list):
  3. @collection.remover
  4. def zark(self, item):
  5. # do something special...
  6. @collection.iterator
  7. def hey_use_this_instead_for_iteration(self):
  8. # ...

There is no requirement to be list-, or set-like at all. Collection classes can be any shape, so long as they have the append, remove and iterate interface marked for SQLAlchemy’s use. Append and remove methods will be called with a mapped entity as the single argument, and iterator methods are called with no arguments and must return an iterator.

Object NameDescription

collection

Decorators for entity collection classes.

class sqlalchemy.orm.collections.``collection

Decorators for entity collection classes.

The decorators fall into two groups: annotations and interception recipes.

The annotating decorators (appender, remover, iterator, converter, internally_instrumented) indicate the method’s purpose and take no arguments. They are not written with parens:

  1. @collection.appender
  2. def append(self, append): ...

The recipe decorators all require parens, even those that take no arguments:

  1. @collection.adds('entity')
  2. def insert(self, position, entity): ...
  3. @collection.removes_return()
  4. def popitem(self): ...
  • method sqlalchemy.orm.collections.collection.static adds(arg)

    Mark the method as adding an entity to the collection.

    Adds “add to collection” handling to the method. The decorator argument indicates which method argument holds the SQLAlchemy-relevant value. Arguments can be specified positionally (i.e. integer) or by name:

    1. @collection.adds(1)
    2. def push(self, item): ...
    3. @collection.adds('entity')
    4. def do_stuff(self, thing, entity=None): ...
  • method sqlalchemy.orm.collections.collection.static appender(fn)

    Tag the method as the collection appender.

    The appender method is called with one positional argument: the value to append. The method will be automatically decorated with ‘adds(1)’ if not already decorated:

    1. @collection.appender
    2. def add(self, append): ...
    3. # or, equivalently
    4. @collection.appender
    5. @collection.adds(1)
    6. def add(self, append): ...
    7. # for mapping type, an 'append' may kick out a previous value
    8. # that occupies that slot. consider d['a'] = 'foo'- any previous
    9. # value in d['a'] is discarded.
    10. @collection.appender
    11. @collection.replaces(1)
    12. def add(self, entity):
    13. key = some_key_func(entity)
    14. previous = None
    15. if key in self:
    16. previous = self[key]
    17. self[key] = entity
    18. return previous

    If the value to append is not allowed in the collection, you may raise an exception. Something to remember is that the appender will be called for each object mapped by a database query. If the database contains rows that violate your collection semantics, you will need to get creative to fix the problem, as access via the collection will not work.

    If the appender method is internally instrumented, you must also receive the keyword argument ‘_sa_initiator’ and ensure its promulgation to collection events.

  • method sqlalchemy.orm.collections.collection.static converter(fn)

    Tag the method as the collection converter.

    Deprecated since version 1.3: The collection.converter() handler is deprecated and will be removed in a future release. Please refer to the bulk_replace listener interface in conjunction with the listen() function.

    This optional method will be called when a collection is being replaced entirely, as in:

    1. myobj.acollection = [newvalue1, newvalue2]

    The converter method will receive the object being assigned and should return an iterable of values suitable for use by the appender method. A converter must not assign values or mutate the collection, its sole job is to adapt the value the user provides into an iterable of values for the ORM’s use.

    The default converter implementation will use duck-typing to do the conversion. A dict-like collection will be convert into an iterable of dictionary values, and other types will simply be iterated:

    1. @collection.converter
    2. def convert(self, other): ...

    If the duck-typing of the object does not match the type of this collection, a TypeError is raised.

    Supply an implementation of this method if you want to expand the range of possible types that can be assigned in bulk or perform validation on the values about to be assigned.

  • method sqlalchemy.orm.collections.collection.static internally_instrumented(fn)

    Tag the method as instrumented.

    This tag will prevent any decoration from being applied to the method. Use this if you are orchestrating your own calls to collection_adapter() in one of the basic SQLAlchemy interface methods, or to prevent an automatic ABC method decoration from wrapping your implementation:

    1. # normally an 'extend' method on a list-like class would be
    2. # automatically intercepted and re-implemented in terms of
    3. # SQLAlchemy events and append(). your implementation will
    4. # never be called, unless:
    5. @collection.internally_instrumented
    6. def extend(self, items): ...
  • method sqlalchemy.orm.collections.collection.static iterator(fn)

    Tag the method as the collection remover.

    The iterator method is called with no arguments. It is expected to return an iterator over all collection members:

    1. @collection.iterator
    2. def __iter__(self): ...
  • method sqlalchemy.orm.collections.collection.static remover(fn)

    Tag the method as the collection remover.

    The remover method is called with one positional argument: the value to remove. The method will be automatically decorated with removes_return() if not already decorated:

    1. @collection.remover
    2. def zap(self, entity): ...
    3. # or, equivalently
    4. @collection.remover
    5. @collection.removes_return()
    6. def zap(self, ): ...

    If the value to remove is not present in the collection, you may raise an exception or return None to ignore the error.

    If the remove method is internally instrumented, you must also receive the keyword argument ‘_sa_initiator’ and ensure its promulgation to collection events.

  • method sqlalchemy.orm.collections.collection.static removes(arg)

    Mark the method as removing an entity in the collection.

    Adds “remove from collection” handling to the method. The decorator argument indicates which method argument holds the SQLAlchemy-relevant value to be removed. Arguments can be specified positionally (i.e. integer) or by name:

    1. @collection.removes(1)
    2. def zap(self, item): ...

    For methods where the value to remove is not known at call-time, use collection.removes_return.

  • method sqlalchemy.orm.collections.collection.static removes_return()

    Mark the method as removing an entity in the collection.

    Adds “remove from collection” handling to the method. The return value of the method, if any, is considered the value to remove. The method arguments are not inspected:

    1. @collection.removes_return()
    2. def pop(self): ...

    For methods where the value to remove is known at call-time, use collection.remove.

  • method sqlalchemy.orm.collections.collection.static replaces(arg)

    Mark the method as replacing an entity in the collection.

    Adds “add to collection” and “remove from collection” handling to the method. The decorator argument indicates which method argument holds the SQLAlchemy-relevant value to be added, and return value, if any will be considered the value to remove.

    Arguments can be specified positionally (i.e. integer) or by name:

    1. @collection.replaces(2)
    2. def __setitem__(self, index, item): ...

Custom Dictionary-Based Collections

The MappedCollection class can be used as a base class for your custom types or as a mix-in to quickly add dict collection support to other classes. It uses a keying function to delegate to __setitem__ and __delitem__:

  1. from sqlalchemy.util import OrderedDict
  2. from sqlalchemy.orm.collections import MappedCollection
  3. class NodeMap(OrderedDict, MappedCollection):
  4. """Holds 'Node' objects, keyed by the 'name' attribute with insert order maintained."""
  5. def __init__(self, *args, **kw):
  6. MappedCollection.__init__(self, keyfunc=lambda node: node.name)
  7. OrderedDict.__init__(self, *args, **kw)

When subclassing MappedCollection, user-defined versions of __setitem__() or __delitem__() should be decorated with collection.internally_instrumented(), if they call down to those same methods on MappedCollection. This because the methods on MappedCollection are already instrumented - calling them from within an already instrumented call can cause events to be fired off repeatedly, or inappropriately, leading to internal state corruption in rare cases:

  1. from sqlalchemy.orm.collections import MappedCollection,\
  2. collection
  3. class MyMappedCollection(MappedCollection):
  4. """Use @internally_instrumented when your methods
  5. call down to already-instrumented methods.
  6. """
  7. @collection.internally_instrumented
  8. def __setitem__(self, key, value, _sa_initiator=None):
  9. # do something with key, value
  10. super(MyMappedCollection, self).__setitem__(key, value, _sa_initiator)
  11. @collection.internally_instrumented
  12. def __delitem__(self, key, _sa_initiator=None):
  13. # do something with key
  14. super(MyMappedCollection, self).__delitem__(key, _sa_initiator)

The ORM understands the dict interface just like lists and sets, and will automatically instrument all dict-like methods if you choose to subclass dict or provide dict-like collection behavior in a duck-typed class. You must decorate appender and remover methods, however- there are no compatible methods in the basic dictionary interface for SQLAlchemy to use by default. Iteration will go through itervalues() unless otherwise decorated.

Note

Due to a bug in MappedCollection prior to version 0.7.6, this workaround usually needs to be called before a custom subclass of MappedCollection which uses collection.internally_instrumented() can be used:

  1. from sqlalchemy.orm.collections import _instrument_class, MappedCollection
  2. _instrument_class(MappedCollection)

This will ensure that the MappedCollection has been properly initialized with custom __setitem__() and __delitem__() methods before used in a custom subclass.

Object NameDescription

MappedCollection

A basic dictionary-based collection class.

class sqlalchemy.orm.collections.``MappedCollection(keyfunc)

A basic dictionary-based collection class.

Extends dict with the minimal bag semantics that collection classes require. set and remove are implemented in terms of a keying function: any callable that takes an object and returns an object for use as a dictionary key.

Class signature

class sqlalchemy.orm.collections.MappedCollection (builtins.dict)

  • method sqlalchemy.orm.collections.MappedCollection.__init__(keyfunc)

    Create a new collection with keying provided by keyfunc.

    keyfunc may be any callable that takes an object and returns an object for use as a dictionary key.

    The keyfunc will be called every time the ORM needs to add a member by value-only (such as when loading instances from the database) or remove a member. The usual cautions about dictionary keying apply- keyfunc(object) should return the same output for the life of the collection. Keying based on mutable properties can result in unreachable instances “lost” in the collection.

  • method sqlalchemy.orm.collections.MappedCollection.clear() → None. Remove all items from D.

  • method sqlalchemy.orm.collections.MappedCollection.pop(k[, d]) → v, remove specified key and return the corresponding value.

    If key is not found, d is returned if given, otherwise KeyError is raised

  • method sqlalchemy.orm.collections.MappedCollection.popitem() → (k, v), remove and return some (key, value) pair as a

    2-tuple; but raise KeyError if D is empty.

  • method sqlalchemy.orm.collections.MappedCollection.remove(value, _sa_initiator=None)

    Remove an item by value, consulting the keyfunc for the key.

  • method sqlalchemy.orm.collections.MappedCollection.set(value, _sa_initiator=None)

    Add an item by value, consulting the keyfunc for the key.

  • method sqlalchemy.orm.collections.MappedCollection.setdefault(key, default=None)

    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.

  • method sqlalchemy.orm.collections.MappedCollection.update([E, ]\*F*) → None. Update D from dict/iterable E and F.

    If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

Instrumentation and Custom Types

Many custom types and existing library classes can be used as a entity collection type as-is without further ado. However, it is important to note that the instrumentation process will modify the type, adding decorators around methods automatically.

The decorations are lightweight and no-op outside of relationships, but they do add unneeded overhead when triggered elsewhere. When using a library class as a collection, it can be good practice to use the “trivial subclass” trick to restrict the decorations to just your usage in relationships. For example:

  1. class MyAwesomeList(some.great.library.AwesomeList):
  2. pass
  3. # ... relationship(..., collection_class=MyAwesomeList)

The ORM uses this approach for built-ins, quietly substituting a trivial subclass when a list, set or dict is used directly.

Collection Internals

Various internal methods.

Object NameDescription

bulk_replace(values, existing_adapter, new_adapter[, initiator])

Load a new collection, firing events based on prior like membership.

collection

Decorators for entity collection classes.

collection_adapter

Fetch the CollectionAdapter for a collection.

CollectionAdapter

Bridges between the ORM and arbitrary Python collections.

InstrumentedDict

An instrumented version of the built-in dict.

InstrumentedList

An instrumented version of the built-in list.

InstrumentedSet

An instrumented version of the built-in set.

prepare_instrumentation(factory)

Prepare a callable for future use as a collection class factory.

function sqlalchemy.orm.collections.``bulk_replace(values, existing_adapter, new_adapter, initiator=None)

Load a new collection, firing events based on prior like membership.

Appends instances in values onto the new_adapter. Events will be fired for any instance not present in the existing_adapter. Any instances in existing_adapter not present in values will have remove events fired upon them.

  • Parameters

    • values – An iterable of collection member instances

    • existing_adapter – A CollectionAdapter of instances to be replaced

    • new_adapter – An empty CollectionAdapter to load with values

class sqlalchemy.orm.collections.``collection

Decorators for entity collection classes.

The decorators fall into two groups: annotations and interception recipes.

The annotating decorators (appender, remover, iterator, converter, internally_instrumented) indicate the method’s purpose and take no arguments. They are not written with parens:

  1. @collection.appender
  2. def append(self, append): ...

The recipe decorators all require parens, even those that take no arguments:

  1. @collection.adds('entity')
  2. def insert(self, position, entity): ...
  3. @collection.removes_return()
  4. def popitem(self): ...

sqlalchemy.orm.collections.``collection_adapter = operator.attrgetter(‘_sa_adapter’)

Fetch the CollectionAdapter for a collection.

class sqlalchemy.orm.collections.``CollectionAdapter(attr, owner_state, data)

Bridges between the ORM and arbitrary Python collections.

Proxies base-level collection operations (append, remove, iterate) to the underlying Python collection, and emits add/remove events for entities entering or leaving the collection.

The ORM uses CollectionAdapter exclusively for interaction with entity collections.

class sqlalchemy.orm.collections.``InstrumentedDict

An instrumented version of the built-in dict.

Class signature

class sqlalchemy.orm.collections.InstrumentedDict (builtins.dict)

class sqlalchemy.orm.collections.``InstrumentedList(iterable=(), /)

An instrumented version of the built-in list.

Class signature

class sqlalchemy.orm.collections.InstrumentedList (builtins.list)

class sqlalchemy.orm.collections.``InstrumentedSet

An instrumented version of the built-in set.

Class signature

class sqlalchemy.orm.collections.InstrumentedSet (builtins.set)

function sqlalchemy.orm.collections.``prepare_instrumentation(factory)

Prepare a callable for future use as a collection class factory.

Given a collection class factory (either a type or no-arg callable), return another factory that will produce compatible instances when called.

This function is responsible for converting collection_class=list into the run-time behavior of collection_class=InstrumentedList.