Can I inspect a sqlalchemy query object to find the already joined tables?

前端 未结 2 1723
遇见更好的自我
遇见更好的自我 2020-12-31 10:27

I\'m trying to programmatically build a search query, and to do so, I\'m joining a table.

class User(db.Model):
    id = db.Column(db.Integer(), primary_key=         


        
相关标签:
2条回答
  • 2020-12-31 10:41

    According to the r-m-n answer:

    Some where in your initialization of your project, add a unique_join method to the sqlalchemy.orm.Query object like this:

    def unique_join(self, *props, **kwargs):
        if props[0] in [c.entity for c in self._join_entities]:
            return self
        return self.join(*props, **kwargs)
    
    Query.unique_join = unique_join
    

    Now use query.unique_join instead of query.join:

    query = query.unique_join(Tag)
    
    0 讨论(0)
  • 2020-12-31 10:57

    You can find joined tables in query._join_entities

    joined_tables = [mapper.class_ for mapper in query._join_entities]
    
    0 讨论(0)
提交回复
热议问题