Is it possible to get a contains_eager collection to follow the
order_by defined in the relationship? It seems like with eager
loading, the order_by defined will just be ignored (which I think make
sense, just wondering if there is a better way than manual sorting).
Here's some sample code to illustrate:
from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import contains_eager, relationship, Session
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, Unicode
Base = declarative_base()
class Contact(Base):
__tablename__ = 'contacts'
id = Column(Integer, primary_key=True)
name = Column(Unicode, nullable=False)
phones = relationship('Phone', back_populates='contact',
order_by='Phone.id')
class Phone(Base):
__tablename__ = 'phones'
id = Column(Integer, primary_key=True)
number = Column(Unicode, nullable=False)
contact_id = Column(Integer, ForeignKey('contacts.id'),
nullable=False)
contact = relationship('Contact', back_populates='phones')
engine = create_engine('sqlite:///:memory:')
engine.echo = True
Base.metadata.create_all(engine)
session = Session(bind=engine)
c = Contact(name=u'Stan Marsh')
c.phones.append(Phone(number=u'999'))
c.phones.append(Phone(number=u'456'))
session.add(c)
session.commit()
session.expire(c)
c = session.query(Contact).one()
# [999, 456]
print [x.number for x in c.phones]
session.expire(c)
query =
session.query(Contact).outerjoin(Contact.phones).order_by(Phone.number)
# If commented, print [999, 456]. Otherwise, print [456, 999]
query = query.options(contains_eager('phones'))
c = query.one()
print [x.number for x in c.phones]
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.