Re: [Sqlalchemy-tickets] [sqlalchemy] #2914: sqlalchemy.orm.mapper.Mapper.attrs doesn't maintain or
Brought to you by:
zzzeek
|
From: sqlalchemy <mi...@zz...> - 2014-01-20 21:51:25
|
#2914: sqlalchemy.orm.mapper.Mapper.attrs doesn't maintain order
-----------------------------------+----------------------------------
Reporter: tisdall | Owner: zzzeek
Type: defect | Status: closed
Priority: low | Milestone: 0.9.xx
Component: orm | Severity: minor - half an hour
Resolution: worksforme | Keywords:
Progress State: completed/closed |
-----------------------------------+----------------------------------
Comment (by zzzeek):
the order of columns when using Declarative is determined by the order in
which each Column is constructed, since otherwise the ordering of items on
a class in Python is unordered. So there is actually significant logic in
order to maintain this ordering within the Table object that's created.
This ordering counter is also shared on relationship objects and such, but
declarative does not pass the objects to the mapper in such a way that
this ordering is maintained; nor does it specify column/relationship
objects as individuals, instead the mapper maps the whole Table object at
once, so there is no way right now that an "interleaved" pattern of plain
columns/relationships can be produced using standard declarative, unless
declarative re-implemented the mapper's usual job of iterating through
table columns which is redundant. the ordering logic thus far is only
concerned with making sure column order on the Table is maintained, as
this results in DDL passed to the database.
probably the most expedient way to sort in object creation order is this:
{{{
from sqlalchemy import inspect
from sqlalchemy.orm import ColumnProperty
mapper = inspect(Person)
def creation_order(obj):
if isinstance(obj, ColumnProperty):
return obj.columns[0]._creation_order
else:
return obj._creation_order
mapper._props.sort(key=lambda k: creation_order(mapper._props[k]))
}}}
why exactly would it be important such that the order in which attributes
are declared on a class be mirrored when inspecting the mapping? This is
not the case for Python builtins such as `dir()`. The attributes on a
Python class are not ordered.
--
Ticket URL: <http://www.sqlalchemy.org/trac/ticket/2914#comment:6>
sqlalchemy <http://www.sqlalchemy.org/>
The Database Toolkit for Python
|