Assume the following model. Note the self-referencing relationship “parent”.
class Widget(object):
__tablename__ = 'widgets'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
parent_id = Column(Integer, ForeignKey('widgets.id'), nullable=True)
parent = relationship("Widget", remote_side=[id])
I am attempting to formulate a query which will allow me to sort by “parent.name”. Specifying joins on the query doesn’t seem to have any affect on the SQL that is generated and executed.
I would be more specific about what I’ve tried thus far, but the thing is, I’ve thrashed all day on this and have pretty much exhausted the available documentation.
Any WAGs on what I should try?
Take a look at the SA docs for self-referencing structures – in particular look at the declaration of
Nodejust before the self-referential section begins.I’m not an expert on these hierarchical setups (they can get a little dicey) but it looks like you have set up your relationship opposite of the examples in the docs. That is not to say you are doing it wrong, but rather that the
Node/Parent/Childrenexample in the docs seems to map to what you’re trying to do. You should be able to set up yourWidgetin the same manner as theNodeexample, get theparentinto your query, and then do the sort.