Reputation: 31
I have a model:
class Examle(models.Model):
date = models.DateTime(auto_add_now=True)
duration = models.IntegerField(default=90) # days
And I want to filter it like so:
Example.objects.filter(date_lt=datetime.today() - timedelta(days=F('duration')))
Of course timedelta
won't take F-object as valid parameter, but hope you got what I mean.
Upvotes: 2
Views: 1967
Reputation: 31
Well, don't think it's the best option but in the end switched to DurationField
like this:
class Examle(models.Model):
date = models.DateTime(auto_add_now=True)
duration = models.DurationField(default=timedelta(days=90)) # days
And used it like this:
Example.objects.filter(date_lt=datetime.now() - F('duration'))
Upvotes: 1
Reputation: 20702
You can't pass F
to timedelta
but you can use it to make a calculation:
timedelta(days=1) * F('duration')
Alternatively, if you're on Django 2.x, try:
Example.objects.annotate(days_before_today=ExtractDay(datetime.today() - F('date'))\
.filter(days_before_today__gte=F('duration'))
Upvotes: 1