按其他字段排序SQLAlchemy关系,而不是按主键

时间:2016-02-08 16:14:54

标签: python sqlalchemy pyramid

我在金字塔应用程序中使用sqlalchemy有以下模型:

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

我可以使用相关表的issues属性来解决问题的相关问题:

for related in db.query(Issue).all()[0].issues:
    print related.status

但是,我没有找到按datetime属性排序问题的解决方案。如果Related具有这样的datetime属性,那么使用关系中的order_by应该非常简单:

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

如何通过其他字段订购相关问题,而不是像现在一样按主键订购?

1 个答案:

答案 0 :(得分:0)

relationship接受关键字参数order_by来处理关系的默认排序。 它应该是这样的:

issues = relationship(iop, foreign_keys=[child_num], order_by="Issue.datetime")

请注意,如果需要处理,则backref函数具有相同的关键字。

在这里,您可以阅读更多关于此主题的http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#building-a-relationship