Date range filter
mauroka opened this issue · 2 comments
Hello.
Is there a way to filter the table based on two dates? I mean, I would like that the filter would be applied on server side. Does django-datatable-view support this?
Thanks a lot for the help.
Mauro.
It's been a year since this was opened, but ranges are allowed by using a hyphen between search terms (optionally padded by spaces on either side). If the term can be successfully split with that pattern, it will generate a __range
query (if the modelfield type supports it).
Columns for ModelFields that don't support __range
will never attempt to build a range query, so there's no danger of the user typing one in and triggering an error.
I tried to do range search using hyphen and it did not work. Either with dates all together or padded with spaces at either side. The solution was to send start_date+'-'+end_date and process it by customizing the class HeadlineColumn(columns.TextColumn):
example.
I used this daterangepicker in my template with following code:
$('#reportrange').on('apply.daterangepicker', function(ev, picker)
{
startdate=picker.startDate.format('DD/MM/YYYY');
enddate=picker.endDate.format('DD/MM/YYYY');
var range = startdate + '-' + enddate;
var datatables = $('.datatable').DataTable();
datatables.columns(3).search(range);
datatables.draw();
});
On server side, I customized the example to:
class DateRangeColumn(columns.DateColumn):
def search(self, model, term):
if '-' in term:
date = term.split('-')
start = datetime.datetime.strptime(date[0], '%d/%m/%Y').strftime('%Y-%m-%d')
end = datetime.datetime.strptime(date[1], '%d/%m/%Y').strftime('%Y-%m-%d')
return Q(headline__range=[start, end])
return super(DateRangeColumn, self).search(model, term)
And it worked fine with date ranges