On Nov 21, 2011, at 12:12 AM, Yap Sok Ann wrote:

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

you can say:

query = 
query.options(contains_eager('phones')).order_by(*Contact.phones.property.order_by)

in that regard, you could generalize:

def my_contains_eager(query, prop):
   return query.options(contains_eager(prop)).order_by(*prop.property.order_by)


query = my_contains_eager(query, Contact.phones)



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

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

Reply via email to