SQLAlchemy - order_by on relationship for join table

后端 未结 3 1551
灰色年华
灰色年华 2021-02-12 20:24

I\'m using declarative SQLAlchemy and I have three models: Role, Permission, and RolePermission. In my Role model, I have t

相关标签:
3条回答
  • 2021-02-12 20:34

    The problem is in permissionLinks relationship. Ordering its items by by Role.name makes no sense to me.

    0 讨论(0)
  • 2021-02-12 20:36

    I couldn't make any of these solutions work, however I found an easier way.

    from sqlalchemy.ext.declarative import declarative_base
    
    class User(Base):
        # ....
        addresses = relationship("Address",
                             order_by="desc(Address.email)",
                             primaryjoin="Address.user_id==User.id")
    

    Found here: http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/relationships.html

    0 讨论(0)
  • 2021-02-12 20:51

    What you want is to order the role attribute of the RolePermission object. Passing order_by sets the order in the Role class.

    Try this:

    from sqlalchemy.orm import backref
    
    permissionLinks = relationship(RolePermission, backref=backref("role", order_by=name))
    

    setting an order for the back reference

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