SQLAlchemy subquery getting AttributeError: 'Query' object has no attribute 'is_clause_element'

Viewed 3338

I am having trouble subquerying from main query function. My query is a function inside a class like this

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

for some reason when I try to do something as simple as the following in another module:

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'    

I am trying to branch off subqueries from the main_query depending on user drop-down selection.

It seems like I cannot run another query from the class, cause when I just simply try this:

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

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

Can someone please help me out here.

1 Answers

You can refer my error :

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

I found out the error was in the class Model;

I changed db.ForeignKey('Model.user_id') to foreign_keys=('Model.user_id) and it solve!

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