SQLAlchemy 0.6 Documentation

Release: 0.6.9 | Release Date: May 5, 2012
SQLAlchemy 0.6 Documentation » SQLAlchemy ORM » ORM Extensions » Ordering List

Ordering List

Ordering List

A custom list that manages index/position information for its children.

author:Jason Kirtland

orderinglist is a helper for mutable ordered relationships. It will intercept list operations performed on a relationship collection and automatically synchronize changes in list position with an attribute on the related objects. (See advdatamapping_entitycollections for more information on the general pattern.)

Example: Two tables that store slides in a presentation. Each slide has a number of bullet points, displayed in order by the ‘position’ column on the bullets table. These bullets can be inserted and re-ordered by your end users, and you need to update the ‘position’ column of all affected rows when changes are made.

slides_table = Table('Slides', metadata,
                     Column('id', Integer, primary_key=True),
                     Column('name', String))

bullets_table = Table('Bullets', metadata,
                      Column('id', Integer, primary_key=True),
                      Column('slide_id', Integer, ForeignKey('Slides.id')),
                      Column('position', Integer),
                      Column('text', String))

 class Slide(object):
     pass
 class Bullet(object):
     pass

 mapper(Slide, slides_table, properties={
       'bullets': relationship(Bullet, order_by=[bullets_table.c.position])
 })
 mapper(Bullet, bullets_table)

The standard relationship mapping will produce a list-like attribute on each Slide containing all related Bullets, but coping with changes in ordering is totally your responsibility. If you insert a Bullet into that list, there is no magic- it won’t have a position attribute unless you assign it it one, and you’ll need to manually renumber all the subsequent Bullets in the list to accommodate the insert.

An orderinglist can automate this and manage the ‘position’ attribute on all related bullets for you.

mapper(Slide, slides_table, properties={
       'bullets': relationship(Bullet,
                           collection_class=ordering_list('position'),
                           order_by=[bullets_table.c.position])
})
mapper(Bullet, bullets_table)

s = Slide()
s.bullets.append(Bullet())
s.bullets.append(Bullet())
s.bullets[1].position
>>> 1
s.bullets.insert(1, Bullet())
s.bullets[2].position
>>> 2

Use the ordering_list function to set up the collection_class on relationships (as in the mapper example above). This implementation depends on the list starting in the proper order, so be SURE to put an order_by on your relationship.

Warning

ordering_list only provides limited functionality when a primary key column or unique column is the target of the sort. Since changing the order of entries often means that two rows must trade values, this is not possible when the value is constrained by a primary key or unique constraint, since one of the rows would temporarily have to point to a third available value so that the other row could take its old value. ordering_list doesn’t do any of this for you, nor does SQLAlchemy itself.

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 ordering_list 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.

Ordering values are not limited to incrementing integers. Almost any scheme can implemented by supplying a custom ordering_func that maps a Python list index to any value you require.

API Reference

sqlalchemy.ext.orderinglist.ordering_list(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 Mapper relationship’s collection_class option. Arguments are:

attr
Name of the mapped attribute to use for storage and retrieval of ordering information
count_from (optional)
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.

Passes along any keyword arguments to OrderingList constructor.