title: Two ways of creating a flask-SQLAlchemy BaseQuery object - only one works, why?
body: <p>This question is a simplification of "<a href="https://stackoverflow.com/questions/15727155/filter-relationships-and-paginate-in-flask-sqlalchemy">Filter relationships and paginate in Flask-SQLAlchemy</a>", and an answer here would probably yield a solution there too.</p>
  
  <p>Say I have a simple model class Design:</p>
  
  <pre><code>from flask import Flask
  from flask.ext.sqlalchemy import SQLAlchemy
  app = Flask(__name__)
  db = SQLAlchemy(app)
  
  class Design(db.Model):
      __tablename__ = 'design'
      id = db.Column(db.Integer, primary_key=True)
      designname = db.Column(db.String(64))
  </code></pre>
  
  <p>I can get a Flask-SQLAlchemy BaseQuery object like this:</p>
  
  <pre><code>&gt;&gt;&gt; Design.query
  &lt;flask_sqlalchemy.BaseQuery object at 0x7f0b29c63990&gt;
  </code></pre>
  
  <p>And I can get data back as you would expect:</p>
  
  <pre><code>&gt;&gt;&gt; Design.query.all()
  [&lt;item1&gt;, &lt;item2&gt;, &lt;item3&gt;]
  </code></pre>
  
  <p>I can also get a BaseQuery object this way (which I think is necessary for more complex query, e.g., one with joins):</p>
  
  <pre><code>&gt;&gt;&gt; db.Query(Design)
  &lt;flask_sqlalchemy.BaseQuery object at 0x7f0b29c6fdd0&gt;
  </code></pre>
  
  <p>It looks like it should be the same object type - indeed, the SQL generated is identical:</p>
  
  <pre><code>&gt;&gt;&gt; str(db.Query(Design)) ==  str(Design.query)
  True
  </code></pre>
  
  <p>And yet, when I try the all() method here, it doesn't work:</p>
  
  <pre><code>&gt;&gt;&gt; db.Query(Design).all()
  Traceback (most recent call last):
  File "&lt;debugger&gt;", line 1, in &lt;module&gt;
  db.Query(Design).all()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2320, in all
  return list(self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2437, in __iter__
  self.session._autoflush()
  AttributeError: 'NoneType' object has no attribute '_autoflush'
  </code></pre>
  
  <p>EDIT: I believe the problem is that the second approach is not attaching a session to the BaseQuery object.  The first method has one:</p>
  
  <pre><code>&gt;&gt;&gt; Design.query.session
  &lt;flask_sqlalchemy.SignallingSession object at 0x7f0b29fbd510&gt;
  </code></pre>
  
  <p>But the other approach does not:</p>
  
  <pre><code>&gt;&gt;&gt; db.Query(Design).session is None
  True
  </code></pre>
  
  <p>Any insight is much appreciated.</p>