Ordering List

    author:

    Jason Kirtland

    is a helper for mutable ordered relationships. It will intercept list operations performed on a relationship()-managed collection and automatically synchronize changes in list position onto a target scalar attribute.

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

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

    The object automates this task, managing the position attribute on all Bullet objects in the collection. It is constructed using the ordering_list() factory:

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

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

    Warning

    only provides limited functionality when a primary key column or unique column is the target of the sort. Operations that are unsupported or are problematic include:

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

    function sqlalchemy.ext.orderinglist.ordering_list(attr: str, count_from: Optional[int] = None, ordering_func: Optional[Callable[[int, Sequence[_T]], int]] = None, reorder_on_append: bool = False) → Callable[[], ]

    Prepares an OrderingList factory for use in mapper definitions.

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

    • Parameters:

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

    Additional arguments are passed to the constructor.

    function sqlalchemy.ext.orderinglist.count_from_0(index, collection)

    Numbering function: consecutive integers starting at 0.

    function sqlalchemy.ext.orderinglist.count_from_1(index, collection)

    Numbering function: consecutive integers starting at 1.

    function sqlalchemy.ext.orderinglist.count_from_n_factory(start)

    Numbering function: consecutive integers starting at arbitrary start.

    class sqlalchemy.ext.orderinglist.OrderingList

    A custom list that manages position information for its children.

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

    Members

    , append(), , pop(), , reorder()

    Class signature

    class (, typing.Generic)

    • method sqlalchemy.ext.orderinglist.OrderingList.__init__(ordering_attr: Optional[str] = None, ordering_func: Optional[Callable[[int, Sequence[_T]], int]] = None, reorder_on_append: bool = False)

      A custom list that manages position information for its children.

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

      • Parameters:

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

        • reorder_on_append

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

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

          Recommend leaving this with the default of False, and just call reorder() if you’re doing operations with previously ordered instances or when doing some housekeeping after manual sql operations.

    • method append(entity)

      Append object to the end of the list.

    • method sqlalchemy.ext.orderinglist.OrderingList.insert(index, entity)

      Insert object before index.

    • method pop(index=-1)

      Remove and return item at index (default last).

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

    • method sqlalchemy.ext.orderinglist.OrderingList.reorder() → None

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