Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow using multiple eav filters in QuerySet #414

Merged
merged 3 commits into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ We follow [Semantic Versions](https://semver.org/) starting at the `0.14.0` rele

### Bug Fixes

- Fixes querying with multiple eav kwargs [#395](https://github.com/jazzband/django-eav2/issues/395)

## 1.4.0 (2023-07-07)

### Features
Expand Down
7 changes: 5 additions & 2 deletions eav/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from django.db.models import Case, IntegerField, Q, When
from django.db.models.query import QuerySet
from django.db.utils import NotSupportedError
from django.db.models import Subquery

from eav.models import Attribute, EnumValue, Value

Expand Down Expand Up @@ -179,8 +180,10 @@ def wrapper(self, *args, **kwargs):
nkey, nval = expand_eav_filter(self.model, key, value)

if nkey in nkwargs:
# Apply AND to both querysets.
nkwargs[nkey] = (nkwargs[nkey] & nval).distinct()
# Add filter to check if matching entity_id is in the previous queryset with same nkey
nkwargs[nkey] = nval.filter(
entity_id__in=nkwargs[nkey].values_list('entity_id', flat=True)
).distinct()
else:
nkwargs.update({nkey: nval})

Expand Down
21 changes: 21 additions & 0 deletions tests/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,24 @@ def test_fk_filter(self):
p = Patient.objects.get_or_create(name='Beth', example=e)[0]
c = ExampleModel.objects.filter(patient=p)
self.assertEqual(c.count(), 1)

def test_filter_with_multiple_eav_attributes(self):
"""
Test filtering a model using both regular and multiple EAV attributes.

This test initializes test data and then filters the Patient test model
based on a combination of a regular attribute and multiple EAV attributes.
"""
self.init_data()

# Use the filter method with 3 EAV attribute conditions
patients = Patient.objects.filter(
name='Anne',
eav__age=3,
eav__illness='cold',
eav__fever='no',
)

# Assert that the expected patient is returned
self.assertEqual(len(patients), 1)
self.assertEqual(patients[0].name, 'Anne')