Skip to content

Commit

Permalink
Merge pull request #67 from miki725/joins
Browse files Browse the repository at this point in the history
not joining already eager loaded models
  • Loading branch information
miki725 authored Aug 8, 2018
2 parents 5442ea4 + 7666119 commit 64b3f14
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
6 changes: 6 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
History
-------

0.3.8 (2018-08-08)
~~~~~~~~~~~~~~~~~~

* Fixed ``SQLAlchemyFilterBackend`` by not joining nested models
when they are already eager loaded via ``query.options()``.

0.3.7 (2018-07-27)
~~~~~~~~~~~~~~~~~~

Expand Down
15 changes: 15 additions & 0 deletions tests/backends/test_sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import six
from alchemy_mock.comparison import ExpressionMatcher
from sqlalchemy import func
from sqlalchemy.orm import joinedload
from sqlalchemy.types import String

from test_project.one_to_one.alchemy import Place, Restaurant, Waiter
Expand Down Expand Up @@ -75,6 +76,20 @@ def test_filter(self, alchemy_db):
'\nWHERE one_to_one_waiter.name ={}'.format(sql.rsplit('=', 1)[-1])
)

def test_filter_already_eagerloaded(self, alchemy_db):
backend = SQLAlchemyFilterBackend(
alchemy_db.query(Place).options(joinedload(Place.restaurant).joinedload(Restaurant.waiter_set)),
)
backend.bind([
FilterSpec(['restaurant', 'waiter_set', 'name'], 'exact', 'John', False),
])

filtered = backend.filter()

sql = six.text_type(filtered)
assert 'place JOIN one_to_one' not in sql
assert 'place LEFT OUTER JOIN one_to_one' in sql

def _test_build_clause(self, alchemy_db, name, lookup, value, expected, is_negated=False):
backend = SQLAlchemyFilterBackend(
alchemy_db.query(Place),
Expand Down
2 changes: 1 addition & 1 deletion url_filter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@

__author__ = 'Miroslav Shubernetskiy'
__email__ = '[email protected]'
__version__ = '0.3.7'
__version__ = '0.3.8'
4 changes: 4 additions & 0 deletions url_filter/backends/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ def build_clause(self, spec):
else:
to_join.append(_field)

existing_eagerloads = [list(i.path) for i in self.queryset._with_options]
if to_join in existing_eagerloads:
to_join = []

builder = getattr(self, '_build_clause_{}'.format(spec.lookup))
column = self._get_attribute_for_field(field)
clause = builder(spec, column)
Expand Down

0 comments on commit 64b3f14

Please sign in to comment.