botvsbot
botvsbot

Reputation: 69

Retrieve sqlalchemy relationship objects in sorted order

I have the following relationship model in sqlalchemy:

class User(Object):

__tablename__ = 'username'

uuid = Column('uuid', BigInteger, primary_key=True, autoincrement=True)
name = Column(String(20))
parent_name = Column(BigInteger, ForeignKey(username.uuid')
children = relationship(
    "User",
    backref=backref("parent_name", remote_side=[uuid]),
    cascade="all, delete, delete-orphan",
    order_by="User.name"
)

When I have a user object from this table, say user, when I retrieve user.children, order_by="User.name" ensures that the list is ordered alphabetically. How can I customize/override the order_by functionality? For example, the name is stored in the db as "Firstname Lastname" and I want user.children to return a list sorted by last name.

Upvotes: 1

Views: 333

Answers (1)

botvsbot
botvsbot

Reputation: 69

The table is already being used and there's a bunch of data which I dont want to migrate. I ended up fixing the problem by overloading the dot-operator: def __getattribute__(self, item): if item == 'children': children = super(User, self).__getattribute__(item) children.sort(key=lambda x: x.name.split(' ')[1]) return children else: return super(User, self).__getattribute__(item)

Upvotes: 1

Related Questions