SQLAlchemy - given a Query object, can you determine if limit has already been applied?
<p>If you do a query like this:</p>

<pre><code>models.Article.query.limit(5).limit(10)
</code></pre>

<p>The limit will actually be 10, the 5 is overridden.  </p>

<p>I have some code that wants to apply a limit to a <code>Query</code>, but only if one hasn't already been applied.  Is there a way to determine if there is a limit already, short of <code>if 'LIMIT' in str(query):</code> ?</p>

<p>From what I understand, you can check if there is a <code>_limit</code> private attribute set:</p>

<pre><code>query = models.Article.query.limit(5)
print(query._limit)  # prints 5

query = models.Article.query
print(query._limit)  # prints None
</code></pre>

<p>This is probably the most direct way to check the presence of an applied limit since the <a href="https://github.com/zzzeek/sqlalchemy/blob/6deb514992ce7d84196fedc191672eae8cc6dc37/lib/sqlalchemy/orm/query.py#L2536" rel="nofollow"><code>limit()</code> method</a> itself is doing exactly that:</p>

<pre><code>@_generative(_no_statement_condition)
def limit(self, limit):
    """Apply a ``LIMIT`` to the query and return the newly resulting

    ``Query``.

    """
    self._limit = limit
</code></pre>

<hr>

<p>You can also do the substring in string check - see if <code>LIMIT</code> is inside the query statement, but this can easily fail if "limit" is used accidentally as a part of column/table name or being a literal "limit" or is present in any other way except having a special meaning.</p>

python sqlalchemy