Reputation: 531
class Parent(db.Model):
id = db.Column(db.Integer, primary_key=True)
role_id = db.Column(db.Integer, db.ForeignKey('role.id')
name = db.Column(db.String())
children = db.relationship('Child', backref='parent')
class Child(db.Model):
id = db.Column(db.Integer, primary_key=True)
parent_id = db.Column(db.Integer, db.ForeignKey('parent.id')
name = db.Column(db.String())
I am trying to order child records by parent role_id:
child_recs = Child.query.order_by(?).all()
I tried by placing order_by attribute in db.relationship(), but it's not working.
children = db.relationship('Child', backref='parent', order_by='Parent.role_id')
Upvotes: 2
Views: 623
Reputation: 531
I got the required results with the help of sorted()
:
child_recs = Child.query.all()
ordered_child_recs = sorted(child_recs, key=lambda rec: rec.parent.role_id)
Upvotes: 1