I have a table called User and Document.
The table User holds:
first_name
…
Document holds:
id
created_by_id
deleted_by_id
…
I want to sort the Document table by the first_name. Therefore, I created the relationships creation_user and deletion_user. Both foreign keys created_by_id and deleted_by_id reference the same table. The hybrid property created_by shall be sorted on:
creation_user = relationship("User", foreign_keys=[created_by_id], lazy="joined")
deletion_user = relationship("User", foreign_keys=[deleted_by_id], lazy="joined")
@hybrid_property
def created_by(self):
if self.creation_user:
return self.creation_user.first_name
else:
return None
@created_by.expression
def created_by(cls):
return User.first_name
Unfortunately, SQLAlchemy does not match the correct user and the resulting SQL query looks like this:
SELECT …
FROM document
LEFT OUTER JOIN [user] AS user_1
ON user_1.id = document.created_by_id
LEFT OUTER JOIN [user] AS user_2
ON user_2.id = document.deleted_by_id
WHERE document.id = ?
ORDER BY [user].first_name ASC
Is there a way to use the hybrid property or a hybrid expression (see sqlalchemy docs) so that the ORDER BY statement resolves to ORDER BY user_2.first_name ASC?