0

My model:

 class Renewal(models.Model):
    policy_number = models.integerField()
    invitation_date = models.DateTimeField()

Snapshot of my table is as follows

id  policy_number     invitation_date 
86  4353    2020-04-21 16:37:39.071941
87  4354    2020-04-21 16:38:16.082238
97  4355    2020-04-21 17:18:03.997882
99  4377    2020-04-21 17:26:58.414530
162 4218    2020-04-22 18:42:23.066879
167 4218    2020-04-22 18:29:10.571033
171 4218    2020-04-22 18:39:17.546550
175 4238    2020-04-23 17:35:54.444945
176 4238    2020-04-23 17:36:01.482819
177 4239    2020-04-23 17:42:15.056850
178 4238    2020-04-24 13:00:06.886101
179 4243    2020-04-24 13:00:32.098504
180 4241    2020-04-24 13:21:31.215547
181 4360    2020-04-29 13:48:18.765400

in my views, I'm trying to get policy_number in a given date range, as follows

def some_function(request):
    start_date = datetime.date.today()
    end_date = start_date - datetime.timedelta(days=5)

    renewals = Renewal.objects.filter(invitation_date__gt=end_date, invitation_date__lte=start_date)
    print(renewals)

what i'm getting : [4238, 4243, 4241] expected answer : [4238, 4243, 4241, 4360]

this should ideally give me all renewal records created in last 5 days. However, if today is 2020-04-29, the last policy record should have been 4360, but my last policy record is 4241

6
  • 1
    Currently your filter checks if invitation_date is >= today and < previous, it should be <= today and > previous. Commented Apr 29, 2020 at 9:01
  • Your 4360 entry's date is not < today. Why would it be in the queryset? Commented Apr 29, 2020 at 9:03
  • I've also tried it this way, renewals = Renewal.objects.filter(invitation_date__gt=end_date, invitation_date__lte=star_date) yet i get the same result Commented Apr 29, 2020 at 9:05
  • I've updated the query in the main question, please review now Commented Apr 29, 2020 at 9:08
  • Can you try with filtering for the date only without time? e.g. invitation_date__date__gt=end_date Commented Apr 29, 2020 at 9:17

1 Answer 1

1

Your Renewal with policy_number = 4360 has the invitation_date = 2020-04-29 13:48:18.765400, so if today is 2020-04-29, then your start_date will be 2020-04-29 00:00:00.0000, so if you want to take that renewal, you can do start_date = datetime.datetime.combine(datetime.datetime.now(), datetime.time.max) if you want to keep invitation_date__lte=start_date, if not, you may take the next day and do invitation_date__lt=start_date

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.