Ordering List

A custom list that manages index/position information for containedelements.

  • author
  • Jason Kirtland

orderinglist is a helper for mutable ordered relationships. It willintercept list operations performed on a relationship()-managedcollection andautomatically synchronize changes in list position onto a target scalarattribute.

Example: A slide table, where each row refers to zero or more entriesin a related bullet table. The bullets within a slide aredisplayed in order based on the value of the position column in thebullet table. As entries are reordered in memory, the value of theposition attribute should be updated to reflect the new sort order:

  1. Base = declarative_base()
  2.  
  3. class Slide(Base):
  4. __tablename__ = 'slide'
  5.  
  6. id = Column(Integer, primary_key=True)
  7. name = Column(String)
  8.  
  9. bullets = relationship("Bullet", order_by="Bullet.position")
  10.  
  11. class Bullet(Base):
  12. __tablename__ = 'bullet'
  13. id = Column(Integer, primary_key=True)
  14. slide_id = Column(Integer, ForeignKey('slide.id'))
  15. position = Column(Integer)
  16. text = Column(String)

The standard relationship mapping will produce a list-like attribute on eachSlide containing all related Bullet objects,but coping with changes in ordering is not handled automatically.When appending a Bullet into Slide.bullets, the Bullet.positionattribute will remain unset until manually assigned. When the Bulletis inserted into the middle of the list, the following Bullet objectswill also need to be renumbered.

The OrderingList object automates this task, managing theposition attribute on all Bullet objects in the collection. It isconstructed using the ordering_list() factory:

  1. from sqlalchemy.ext.orderinglist import ordering_list
  2.  
  3. Base = declarative_base()
  4.  
  5. class Slide(Base):
  6. __tablename__ = 'slide'
  7.  
  8. id = Column(Integer, primary_key=True)
  9. name = Column(String)
  10.  
  11. bullets = relationship("Bullet", order_by="Bullet.position",
  12. collection_class=ordering_list('position'))
  13.  
  14. class Bullet(Base):
  15. __tablename__ = 'bullet'
  16. id = Column(Integer, primary_key=True)
  17. slide_id = Column(Integer, ForeignKey('slide.id'))
  18. position = Column(Integer)
  19. text = Column(String)

With the above mapping the Bullet.position attribute is managed:

  1. s = Slide()
  2. s.bullets.append(Bullet())
  3. s.bullets.append(Bullet())
  4. s.bullets[1].position
  5. >>> 1
  6. s.bullets.insert(1, Bullet())
  7. s.bullets[2].position
  8. >>> 2

The OrderingList construct only works with changes to acollection, and not the initial load from the database, and requires that thelist be sorted when loaded. Therefore, be sure to specify order_by on therelationship() against the target ordering attribute, so that theordering is correct when first loaded.

Warning

OrderingList only provides limited functionality when a primarykey column or unique column is the target of the sort. Operationsthat are unsupported or are problematic include:

  • two entries must trade values. This is not supported directly in thecase of a primary key or unique constraint because it means at leastone row would need to be temporarily removed first, or changed toa third, neutral value while the switch occurs.

  • an entry must be deleted in order to make room for a new entry.SQLAlchemy’s unit of work performs all INSERTs before DELETEs within asingle flush. In the case of a primary key, it will tradean INSERT/DELETE of the same primary key for an UPDATE statement in orderto lessen the impact of this limitation, however this does not take placefor a UNIQUE column.A future feature will allow the “DELETE before INSERT” behavior to bepossible, alleviating this limitation, though this feature will requireexplicit configuration at the mapper level for sets of columns thatare to be handled in this way.

ordering_list() takes the name of the related object’s orderingattribute as an argument. By default, the zero-based integer index of theobject’s position in the ordering_list() is synchronized with theordering attribute: index 0 will get position 0, index 1 position 1, etc. Tostart numbering at 1 or some other integer, provide count_from=1.

API Reference

  • sqlalchemy.ext.orderinglist.orderinglist(_attr, count_from=None, **kw)
  • Prepares an OrderingList factory for use in mapper definitions.

Returns an object suitable for use as an argument to a Mapperrelationship’s collection_class option. e.g.:

  1. from sqlalchemy.ext.orderinglist import ordering_list
  2.  
  3. class Slide(Base):
  4. __tablename__ = 'slide'
  5.  
  6. id = Column(Integer, primary_key=True)
  7. name = Column(String)
  8.  
  9. bullets = relationship("Bullet", order_by="Bullet.position",
  10. collection_class=ordering_list('position'))
  • Parameters
    • attr – Name of the mapped attribute to use for storage and retrieval ofordering information

    • count_from – Set up an integer-based ordering, starting at count_from. Forexample, ordering_list('pos', count_from=1) would create a 1-basedlist in SQL, storing the value in the ‘pos’ column. Ignored ifordering_func is supplied.

Additional arguments are passed to the OrderingList constructor.

  • sqlalchemy.ext.orderinglist.countfrom_0(_index, collection)
  • Numbering function: consecutive integers starting at 0.

  • sqlalchemy.ext.orderinglist.countfrom_1(_index, collection)

  • Numbering function: consecutive integers starting at 1.

  • sqlalchemy.ext.orderinglist.countfrom_n_factory(_start)

  • Numbering function: consecutive integers starting at arbitrary start.

  • class sqlalchemy.ext.orderinglist.OrderingList(ordering_attr=None, ordering_func=None, reorder_on_append=False)

  • Bases: builtins.list

A custom list that manages position information for its children.

The OrderingList object is normally set up using theordering_list() factory function, used in conjunction withthe relationship() function.

  • init(ordering_attr=None, ordering_func=None, reorder_on_append=False)
  • A custom list that manages position information for its children.

OrderingList is a collection_class list implementation thatsyncs position in a Python list with a position attribute on themapped objects.

This implementation relies on the list starting in the proper order,so be sure to put an order_by on your relationship.

  1. - Parameters
  2. -
  3. -

ordering_attr – Name of the attribute that stores the object’s order in therelationship.

  1. -

ordering_func

Optional. A function that maps the position inthe Python list to a value to store in theordering_attr. Values returned are usually (but need not be!)integers.

An ordering_func is called with two positional parameters: theindex of the element in the list, and the list itself.

If omitted, Python list indexes are used for the attribute values.Two basic pre-built numbering functions are provided in this module:count_from_0 and count_from_1. For more exotic exampleslike stepped numbering, alphabetical and Fibonacci numbering, seethe unit tests.

  1. -

reorder_on_append

Default False. When appending an object with an existing (non-None)ordering value, that value will be left untouched unlessreorder_on_append is true. This is an optimization to avoid avariety of dangerous unexpected database writes.

SQLAlchemy will add instances to the list via append() when yourobject loads. If for some reason the result set from the databaseskips a step in the ordering (say, row ‘1’ is missing but you get‘2’, ‘3’, and ‘4’), reorder_on_append=True would immediatelyrenumber the items to ‘1’, ‘2’, ‘3’. If you have multiple sessionsmaking changes, any of whom happen to load this collection even inpassing, all of the sessions would try to “clean up” the numberingin their commits, possibly causing all but one to fail with aconcurrent modification error.

Recommend leaving this with the default of False, and just callreorder() if you’re doing append() operations withpreviously ordered instances or when doing some housekeeping aftermanual sql operations.

  • append(entity)
  • Append object to the end of the list.

  • insert(index, entity)

  • Insert object before index.

  • pop(index=-1)

  • Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

  • remove(entity)
  • Remove first occurrence of value.

Raises ValueError if the value is not present.

  • reorder()
  • Synchronize ordering for the entire collection.

Sweeps through the list and ensures that each object has accurateordering information set.