-1

I have

Class Profile(models.Model)
    turn_off_date = models.DateTimeField(null= True, blank = True,auto_now = False)

I need to find all profile records, that have expiration date= Exactly x days from now. How do I do this? I can think of iterating through all profiles and manually comparing dates, but it seems not effective

Update:

I neeed to filter by date, not by datetime field as in duplicate question

Right now I am doing it like this:

profiles = Profile.objects.all()
for profile in profiles:
        if(profile.days_left() == x):
           print(profile.days_left())

And in my Profile model I defined a method:

def days_left(self):
        turn_off_date = self.turn_off_date

        days_left = (turn_off_date - datetime.now()).days
        if days_left < 0:
            days_left = 0
        return days_left
user2950593
  • 9,233
  • 15
  • 67
  • 131

3 Answers3

0

You can use range to achieve this,

Example:

Profile.objects.filter(turn_off_date__range=(start_date, end_date))
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
0

You can just query by __date with a given date

For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value.

.filter(turn_off_date__date=(datetime.now()+timedelta(days=x)).date())
Sayse
  • 42,633
  • 14
  • 77
  • 146
0

I guess something like this will work fine:

From Django 1.9 you can use the __date field lookup, exactly as you have mentioned in your question. For older versions, you will have to do with the other methods.

Thanks to https://stackoverflow.com/a/45735324/2950593

user2950593
  • 9,233
  • 15
  • 67
  • 131