React/Django app. I want to add a date range filter (flatpickr) to already existing filters for orders. Orders has a period
field (how long the order is valid), which is a DateRange
field. Via the flatpickr I select a date range, and if at least one day of the order period is in that selected date range, it should show up as a result.
ex. period: DateRange(datetime.date(2021, 2, 11), datetime.date(2021, 3, 14), '[)')
I have the filter ready in FE to accept the results from BE. But I'm not sure how to achieve this in the BE. As I'm fairly new to this, my ideas are limited, but currently have this:
...
from django_filters.rest_framework import DjangoFilterBackend, IsoDateTimeFilter, FilterSet
from rest_framework import filters, mixins, status
...
class OrderFilter(FilterSet):
start_date = IsoDateTimeFilter(field_name="period", lookup_expr="gte")
end_date = IsoDateTimeFilter(field_name="period", lookup_expr="lte")
class Meta:
model = Order
fields = {
"status": ["in"],
"client": ["exact"],
"created_by": ["exact"],
}
ordering_fields = ["period", "client__name", "destination__name"]
ordering = ["period"]
custom_field_target_model = Order
I believe the closest thing I found, is IsoDateTimeFromToRangeFilter, but that doesn't seem to be what I'm looking for.
CodePudding user response:
For DateRangeField
you can use DateFromToRangeFilter
. Since filters work with field types, you need to check field_class value of the filter.
class DateFromToRangeFilter(RangeFilter):
field_class = DateRangeField
If you want to filter start & end date/datetime(s) separately, you can both validate if the given input is in period or not. You can also lookup with range
for DateRangeFields.
queryset.filter(created_at__range=(start_date, end_date))
this should work in your case also.
Not: As @aberkb mentioned, you need to add "period" to fields.
CodePudding user response:
you need to add start_date and end_date to your meta fields in order them to work