backref in polymorphic relationship doesn't maintain order

Issue #321 resolved
Former user created an issue

(I'm not sure whether this should be considered a bug or a feature request)

In the example polymorph.py, 5 employees are added to the company.employees list, and are then saved. When the company is loaded back from the database again, this list is populated in a different order.

From the unit of work dump, it looks like they are being added to the database by class (so Person objects are added first, followed by Manager objects, then Engineer). I would have expected the employees to be added in the order that they were created, but I don't know if this is even possible with the way sqlalchemy builds its dependency graph.

I can work around this by adding an extra property to (my equivalent of) the Person class as a 'sequence number', but it seems like a kludge. Is there any way of forcing the order in which these items get inserted into the database?

Thanks a lot,

Simon

Comments (4)

  1. Mike Bayer repo owner
    • changed milestone to 0.4.0

    its usually not reliable to depend on insert ordering as a means to get things back in that order..unless youre just ordering by primary key. its true that SA tries to do what hibernate does which is insert things in the order that they were added to the session. this would require a refactor to the mapper/uow's method of saving inherited items, such that mapper's save_obj method would function across multiple mappers and do some trickier stuff regarding the list of tables that it loops through (the list of tables would be the aggrgate of all tables used in a particular inheritance hierarchy).

  2. Mike Bayer repo owner

    yeah, ive taken a look, we can and should totally do this, and the refactoring is largely straightfoward...the step at which we save objects (as well as delete...) by class up an inheritance hierarchy can easily be changed to sort the individual instances across classes, and still do things in "table" order. the unitofwork has already been largely cleaned up in the trunk (see UOWExecutor in unitofwork.py, new uowdumper implementation that builds on it) and this will continue to build on that. hopefully ill get some time before next week to get this done.

  3. Log in to comment