【问题标题】:SQLAlchemy subquery getting AttributeError: 'Query' object has no attribute 'is_clause_element'SQLAlchemy 子查询获取 AttributeError:“查询”对象没有属性“is_clause_element”
【发布时间】:2019-04-07 05:52:36
【问题描述】:

我在从主查询函数进行子查询时遇到问题。我的查询是这样的类中的一个函数

class MyClass():
    ...
    ...
    @property
    def main_query(self):
        main_query = session.query(MainTable)
                            .join(otherTable)
                            .filter(otherTable.id = self.id)
        return main_query

由于某种原因,当我尝试在另一个模块中做如下简单的事情时:

q = MyClass.main_query(111)   # 111 is the id here
print(str(q))                 # I can see this print, it prints the correct query statement
subquery_maxdate = session.query(func.max(Table1.date).label("max_date")).subquery()
query = DBSession.query(q, subquery_maxdate)    #This gives me an error  

AttributeError: 'Query' object has no attribute 'is_clause_element'    

我正在尝试根据用户下拉选择从main_query 中分离子查询。

似乎我无法从该类运行另一个查询,因为当我只是尝试这个时:

q = DBSession.query(q)   # This already gives me the error

AttributeError: 'Query' object has no attribute 'is_clause_element'

谁能帮帮我。

【问题讨论】:

  • 我在类似的设置中遇到了同样的问题,但尚未解决。
  • 有点沮丧,这个问题没有更详细的答案:(
  • 我知道这已经晚了,但这可能是因为main_query 的返回是Query 对象而不是子查询。可能在.filter(otherTable.id ... 解决问题后添加.subquery()

标签: python python-3.x sqlalchemy


【解决方案1】:

你可以参考我的错误:

AttributeError: 'ForeignKey' 对象没有属性 'is_clause_element'

我发现错误出现在 Model 类中;

我将 db.ForeignKey('Model.user_id') 更改为 foreign_keys=('Model.user_id) 并解决了!

class User(UserMixin, db.Model):
    ...
    ...
    message = db.relationship('Message', foreign_keys='Message.user_id')
    #note that I use db.relationship NOT db.Column

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    相关资源
    最近更新 更多