How do I get the objects pointed to by a many-to-many association proxy to 
be sorted? In the example below, adding order_by=b.order to the backref() 
produces AttributeError: 'RelationshipProperty' object has no attribute 
'order', and adding order_by="b.order" produces AttributeError: 'Table' 
object has no attribute 'order'. Is it possible to somehow specify order_by 
so that the a.bs are automatically sorted by b.order?

Thanks!

Seth

from sqlalchemy import Column, Integer, ForeignKey, create_engine
from sqlalchemy.orm import create_session, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy

sqlite = 'sqlite:///test_a_to_b.db'
e = create_engine(sqlite, echo=False)
Base = declarative_base(bind=e)

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    bs = association_proxy("a_to_b", "b", creator=lambda x: A_to_B(b=x))

class B(Base):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)
    order = Column(Integer)

class A_to_B(Base):
    __tablename__ = 'a_to_b'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey(str(A.__table__) + ".id"), 
nullable=False, index=True)
    b_id = Column(Integer, ForeignKey(str(B.__table__) + ".id"), 
nullable=False)
    b = relationship(B, foreign_keys=[b_id])
    a = relationship(A, foreign_keys=[a_id],
                     backref=backref("a_to_b", lazy="subquery", 
cascade="all, delete-orphan"))  # , order_by="b.order"))
    def __init__(self, a=None, b=None):
        self.a = a
        self.b = b

if __name__ == '__main__':
    Base.metadata.drop_all()
    Base.metadata.create_all()
    session = create_session(bind=e, autocommit=False)
    a = A(bs=[B(order=10), B(order=2)])
    session.add(a)
    session.commit()
    a = session.query(A).one()
    for b in a.bs:
        print b.order
    session.close_all()

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to