python - Ordering SQLAlchemy relationship by another field, not by primary key -
i have following model using sqlalchemy in pyramid application:
class issue(base_iop): __tablename__ = 'issues' issueid = column(bigint, primary_key=true, name="issueid") issuenum = column(varchar(20), name="issuenum") status = column(varchar(32), name="status") datetime = column(timestamp, name="issuetime") class related(base_iop): __tablename__ = 'related' relationid = column(bigint, primary_key=true, name="rowstamp") parent_num = column(varchar(20), foreignkey('issue.issuenum'),name="recordkey") children_num = column(varchar(20), foreignkey('issue.issuenum'), name="relatedkey") issues = relationship(iop, foreign_keys=[child_num])
i can related issues of issue fine using: issues
attribute of related table:
for related in db.query(issue).all()[0].issues: print related.status
however, didn't find solution order issues datetime
attribute. if related
had datetime attribute this, should pretty straightforward using order_by in relationship:
class issue(base_iop): __tablename__ = 'issues' issueid = column(bigint, primary_key=true, name="issueid") issuenum = column(varchar(20), name="issuenum") status = column(varchar(32), name="status") datetime = column(timestamp, name="issuetime") children = relationship("related", foreign_keys="[related.parent_num]", backref="parent", order_by="[related.datetime]") class related(base_iop): __tablename__ = 'related' relationid = column(bigint, primary_key=true, name="rowstamp") parent_num = column(varchar(20), foreignkey('issue.issuenum'),name="recordkey") children_num = column(varchar(20), foreignkey('issue.issuenum'), name="relatedkey") datetime = column(timestamp, name="issuetime") issues = relationship(iop, foreign_keys=[child_num])
how order related issues field, not primary key now?
relationship accept keyword argument order_by handle default ordering of relation. should somthing like:
issues = relationship(iop, foreign_keys=[child_num], order_by="issue.datetime")
note backref function has same keyword, if need handle that.
here can read more: http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#building-a-relationship on topic
Comments
Post a Comment