]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
Improve error message when using :meth:`_query.Query.filter_by` in
authorFederico Caselli <cfederico87@gmail.com>
Thu, 14 May 2020 19:51:59 +0000 (21:51 +0200)
committerFederico Caselli <cfederico87@gmail.com>
Fri, 15 May 2020 16:43:15 +0000 (18:43 +0200)
a query where the first entity is not a mapped class.

Fixes: #5260
Change-Id: I18cfccc0f3e587cb3df3e1f5f23b6885d5f2f466
(cherry picked from commit 8c10e29dc7aa2356d0f3f5110b2c9dade9d87096)

doc/build/changelog/unreleased_13/5260.rst [new file with mode: 0644]
lib/sqlalchemy/orm/query.py
test/orm/test_query.py

diff --git a/doc/build/changelog/unreleased_13/5260.rst b/doc/build/changelog/unreleased_13/5260.rst
new file mode 100644 (file)
index 0000000..18e1dde
--- /dev/null
@@ -0,0 +1,6 @@
+.. change::
+    :tags: usecase, orm
+    :tickets: 5326
+
+    Improve error message when using :meth:`_query.Query.filter_by` in
+    a query where the first entity is not a mapped class.
index e6da753f8969733dcd0c650fd9ec6a9e369ef0e0..23c08042b75287b95461db4c925b139ffc1a5643 100644 (file)
@@ -1890,8 +1890,17 @@ class Query(object):
 
         """
 
+        zero = self._joinpoint_zero()
+        if zero is None:
+            raise sa_exc.InvalidRequestError(
+                "Can't use filter_by when the first entity '%s' of a query "
+                "is not a mapped class. Please use the filter method instead, "
+                "or change the order of the entities in the query"
+                % self._query_entity_zero()
+            )
+
         clauses = [
-            _entity_descriptor(self._joinpoint_zero(), key) == value
+            _entity_descriptor(zero, key) == value
             for key, value in kwargs.items()
         ]
         return self.filter(*clauses)
index 77a820953ceea6f4a57107c42d5bade9f0e4801b..df1cf27a7a67046ce4a177d1de130fc08f5dc35a 100644 (file)
@@ -3197,6 +3197,18 @@ class FilterTest(QueryTest, AssertsCompiledSQL):
             "AS users_name FROM users WHERE name='ed'",
         )
 
+    def test_filter_by_non_entity(self):
+        s = create_session()
+        e = sa.func.count(123)
+        assert_raises_message(
+            sa_exc.InvalidRequestError,
+            r"Can't use filter_by when the first entity 'count\(:count_1\)' of"
+            " a query is not a mapped class. Please use the filter method "
+            "instead, or change the order of the entities in the query",
+            s.query(e).filter_by,
+            col=42,
+        )
+
 
 class HasAnyTest(fixtures.DeclarativeMappedTest, AssertsCompiledSQL):
     __dialect__ = "default"