Use raw SQL in an ORM query

前端 未结 2 845
情话喂你
情话喂你 2021-01-15 20:30

Is it possible to make edits or override the ORM\'s generated SQL with your own raw SQL? Or is the ORM expected to be flexible enough to build pretty much any query I could

相关标签:
2条回答
  • 2021-01-15 21:00

    You can build it by aliasing the Model first and then using that alias as the second table to an outer join. The following assumes that you already have a session that is bound to a working engine:

    from sqlalchemy.orm import aliased
    from sqlalchemy import and_
    
    
    allocation_status2 = aliased(AllocationStatus)
    session.query(AllocationStatus).\
        outerjoin(allocation_status2,
                  and_(AllocationStatus.allocation_id == allocation_status2.allocation_id,
                       AllocationStatus.id < allocation_status2.id)).\
        filter(allocation_status2.id.is_(None)).all()
    

    I hope this helps.

    0 讨论(0)
  • 2021-01-15 21:05

    The answer by @Abdou is the proper way to go, but you could also run your textual SQL using Query.from_statement():

    session.query(AllocationStatus).\
        from_statement(text("""
            SELECT allocation_status.*
            FROM allocation_status
            LEFT JOIN allocation_status allocation_status2
                   ON allocation_status.allocation_id = allocation_status2.allocation_id
                  AND allocation_status.id < allocation_status2.id
            WHERE allocation_status2.id IS NULL;""")).\
        all()
    

    Note the use of text().

    0 讨论(0)
提交回复
热议问题