From 6913dc20e8485384de95ef3ef6d5edf401f3d9c5 Mon Sep 17 00:00:00 2001 From: Jerome Lefeuvre Date: Wed, 15 Dec 2021 15:43:05 -0500 Subject: [PATCH] Fix #7 : Add possibility to filter on nested field more than 1 level --- daterangefilter/filters.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/daterangefilter/filters.py b/daterangefilter/filters.py index 4b9e6f0..6fefbba 100644 --- a/daterangefilter/filters.py +++ b/daterangefilter/filters.py @@ -22,12 +22,14 @@ def __init__(self, field, request, params, model, model_admin, field_path): if self.lookup_gte and self.lookup_lte: self.lookup_val = '{} - {}'.format(self.lookup_gte, self.lookup_lte) # if we are filtering DateTimeField we should add one day to final date - if "__" in field_path: - related_model, field = field_path.split("__") - field = model._meta.get_field(related_model).related_model._meta.get_field(field) - else: - field = model._meta.get_field(field_path) - + new_field_path = field_path + nested_model = model + while len(new_field_path.split('__')) > 1: + related_model, new_field_path = new_field_path.split("__")[0], '__'.join(new_field_path.split("__")[1:]) + nested_model = nested_model._meta.get_field(related_model).related_model + + field = nested_model._meta.get_field(new_field_path) + if isinstance(field, models.DateTimeField): try: gte_date = datetime.datetime.strptime(self.lookup_gte, '%Y-%m-%d')