Skip to content

Commit c1a48d5

Browse files
author
Ryan P Kilby
committed
Fix methodfilter test to work on non-relationship filters
1 parent 77a318a commit c1a48d5

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

tests/filters.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,22 @@ class Meta:
7171
model = Post
7272

7373
def filter_is_published(self, name, qs, value):
74+
"""
75+
`is_published` is based on the actual `date_published`.
76+
If the publishing date is null, then the post is not published.
77+
"""
78+
# convert value to boolean
7479
null = value.lower() != 'true'
7580

76-
# 'post', 'is_published'
77-
name, _ = name.rsplit(LOOKUP_SEP, 1)
81+
# The lookup name will end with `is_published`, but could be
82+
# preceded by a related lookup path.
83+
if LOOKUP_SEP in name:
84+
rel, _ = name.rsplit(LOOKUP_SEP, 1)
85+
name = LOOKUP_SEP.join([rel, 'date_published__isnull'])
86+
else:
87+
name = 'date_published__isnull'
7888

79-
return qs.filter(**{
80-
LOOKUP_SEP.join([name, 'date_published__isnull']): null
81-
})
89+
return qs.filter(**{name: null})
8290

8391

8492
class CoverFilterWithRelatedMethodFilter(FilterSet):

tests/test_filterset.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
NoteFilterWithRelatedAll,
2323
NoteFilterWithRelatedAllDifferentFilterName,
2424
PostFilterWithRelated,
25-
# PostFilterWithMethod,
25+
PostFilterWithMethod,
2626
CoverFilterWithRelatedMethodFilter,
2727
CoverFilterWithRelated,
2828
# PageFilterWithRelated,
@@ -345,11 +345,20 @@ def generateTestData(cls):
345345
note2 = Note.objects.create(title="Test 2", content="Test content 2", author=user)
346346

347347
post1 = Post.objects.create(note=note1, content="Test content in post 1")
348-
post2 = Post.objects.create(note=note2, content="Test content in post 4", date_published=datetime.date.today())
348+
post2 = Post.objects.create(note=note2, content="Test content in post 2", date_published=datetime.date.today())
349349

350350
Cover.objects.create(post=post1, comment="Cover 1")
351351
Cover.objects.create(post=post2, comment="Cover 2")
352352

353+
def test_method_filter(self):
354+
GET = {
355+
'is_published': 'true'
356+
}
357+
filterset = PostFilterWithMethod(GET, queryset=Post.objects.all())
358+
results = list(filterset)
359+
self.assertEqual(len(results), 1)
360+
self.assertEqual(results[0].content, "Test content in post 2")
361+
353362
def test_related_method_filter(self):
354363
"""
355364
Missing MethodFilter filter methods are silently ignored, returning

0 commit comments

Comments
 (0)