How to order elements when accesed by many to many relation in pythons SQLAlchemy?
Assuming two models in a many to many relationship:
parent_child = Table('parent_child', metadata,
Column('parent_id', Integer, ForeignKey('parent.id')),
Column('child_id', Integer, ForeignKey('children.id')))
class Parents(Base):
__tablename__ = 'parents'
__table_args__ = {'autoload' : True} # reflecting database
children = relationship('Child',
secondary=parent_chi开发者_StackOverflowld, # What goes here for sorting?
backref='parents')
class Child(Base):
__tablename__ = 'children'
__table_args__ = {'autoload' : True} # reflecting database
I know I can do
parent = session.query(Parent).first()
to get the first parent element in the table. Doing
parent.children
returns all children of the given parent. What if I want to sort them let's say by birthdate (assuming the model Child
has column birthdate
)?
there's an order_by
keyword argument available for relationship. here
Also your missing the s
in the parent = session.query(Parents).first()
and the s
in the ForeignKey
children = relationship('Child', secondary=parent_child, order_by='Child.birthdate', backref='parents')
精彩评论