Skip to content

Commit

Permalink
Add the last_days filter to changeset list view
Browse files Browse the repository at this point in the history
  • Loading branch information
willemarcel committed Jul 19, 2021
1 parent d000e88 commit e2dcea7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
10 changes: 10 additions & 0 deletions osmchadjango/changeset/filters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from datetime import date, timedelta

from django.contrib.gis.geos import Polygon
from django.db.models import Count
Expand Down Expand Up @@ -171,6 +172,11 @@ class ChangesetFilter(GeoFilterSet):
help_text="""Filter changesets whose number of comments are lower than
or equal to a number."""
)
last_days = filters.NumberFilter(
field_name='date',
method='get_past_n_days',
help_text="Filter changesets whose date is not older than a determined number of days"
)
date__gte = filters.DateTimeFilter(
field_name='date',
lookup_expr='gte',
Expand Down Expand Up @@ -256,6 +262,10 @@ class ChangesetFilter(GeoFilterSet):
help_text="""Filter changesets by the metadata fields."""
)

def get_past_n_days(self, queryset, field_name, value):
start_date = date.today() - timedelta(days=int(value))
return queryset.filter(date__gte=start_date)

def filter_metadata(self, queryset, name, value):
values = [
[i.strip() for i in t.split('=')] # remove leading and ending spaces
Expand Down
25 changes: 25 additions & 0 deletions osmchadjango/changeset/tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,31 @@ def test_number_field_filters(self):
self.assertEqual(ChangesetFilter({'comments_count__gte': 5}).qs.count(), 2)
self.assertEqual(ChangesetFilter({'comments_count__gte': 11}).qs.count(), 0)

def test_last_days_filter(self):
ChangesetFactory(date=date.today() - timedelta(days=5))

self.assertEqual(
ChangesetFilter({'last_days': 0}).qs.count(), 4
)
self.assertEqual(
ChangesetFilter({'last_days': 1}).qs.count(), 4
)
self.assertEqual(
ChangesetFilter({'last_days': 2}).qs.count(), 4
)
self.assertEqual(
ChangesetFilter({'last_days': 3}).qs.count(), 4
)
self.assertEqual(
ChangesetFilter({'last_days': 4}).qs.count(), 4
)
self.assertEqual(
ChangesetFilter({'last_days': 5}).qs.count(), 5
)
self.assertEqual(
ChangesetFilter({'last_days': 6}).qs.count(), 5
)

def test_date_field_filter(self):
tomorrow = date.today() + timedelta(days=1)
yesterday = date.today() - timedelta(days=1)
Expand Down

0 comments on commit e2dcea7

Please sign in to comment.