在SQLAlchemy中按子对象的字段排序?

时间:2016-03-20 08:55:12

标签: python sqlalchemy

我想查询Reference的特定对象。但我希望该列表按其子对象排序(您可以说是关系):Reference._periodical._nameReference._author._lastname' (means the __first__ author, which are orded by ReferenceAuthor.Index`)。

无法看到如何做到这一点。这是查询但没有订购。

return self.session.query(Reference) \
         .filter_by(_mark = False) \
         #.order_by(Reference._periodical) \
         #.order_by(Reference._author._lastname) \
         .all()

这是模型本身

ReferenceAuthor = sa.Table('ReferenceAuthor', _Base.metadata,
        sa.Column('ReferenceID',  sa.Integer, sa.ForeignKey('Reference.ID'), primary_key=True),
        sa.Column('PersonID', sa.Integer, sa.ForeignKey('Person.ID'), primary_key=True),
        sa.Column('Index', sa.Integer)
        )


class Reference(_Base):
    __tablename__ = 'Reference'

    _id = sa.Column('ID', sa.Integer, primary_key=True)
    _mark = sa.Column('HasLabel', sa.Boolean)

    # Autor
    _authors = sao.relationship('Person', secondary=ReferenceAuthor,
            order_by=ReferenceAuthor.c.Index)

    # Journal
    _periodical_fk = sa.Column('PeriodicalID',
                                sa.Integer,
                                sa.ForeignKey('Periodical.ID'))
    _periodical = sao.relationship('Periodical')


class Periodical(_Base):
    __tablename__ = 'Periodical'

    _id = sa.Column('ID', sa.Integer, primary_key=True)
    _name = sa.Column('Name', sa.String)


class Person(_Base):
    __tablename__ = 'Person'

    _id = sa.Column('ID', sa.Integer, primary_key=True)
    _lastname = sa.Column('LastName', sa.String)

1 个答案:

答案 0 :(得分:1)

据我所知,你不能这样使用SQLAlchemy。这些关系仅适用于Reference的实例。一种方法是通过column propertieshybrid attributes,但我找到的最明确的方法是只进行连接然后进行排序。这样做的方法如下:

stmnt = session.query(Reference) \
        .join(Periodical) \
        .order_by(Periodical._name) \
        .filter(Reference._mark == False)

print(stmnt)

这导致以下sql代码:

SELECT "Reference"."ID" AS "Reference_ID", "Reference"."HasLabel" AS "Reference_HasLabel", "Reference"."PeriodicalID" AS "Reference_PeriodicalID" 
FROM "Reference" JOIN "Periodical" ON "Periodical"."ID" = "Reference"."PeriodicalID" 
WHERE "Reference"."HasLabel" = 0 ORDER BY "Periodical"."Name"

根据您的意见,如果您想将其扩展为包含此人,则需要以下内容:

stmnt = session.query(Reference).\
    filter_by(_mark=False).\
    join(Periodical).\
    join(ReferenceAuthor, and_(ReferenceAuthor.c.ReferenceId == Reference.ID), ReferenceAuthor.c.Index == 0)).\
    join(Person).\
    order_by(Periodical._name).\
    order_by(Person._lastname)