Artyom Tsoy
Artyom Tsoy

Reputation: 2238

Django ORM - get records that are older than record's `duration` days

I have the model:

class Plan(models.Model):
  date = models.DateTimeField()
  duration = models.DurationField(default=30)

I want to get the records that are older than today - duration with ORM. Is it possible? Maybe something like Plan.objects.filter(date__lt='self.duration') exists?

Upvotes: 0

Views: 458

Answers (2)

chirag soni
chirag soni

Reputation: 1026

Yes you can do like this:

Plan.objects.filter(duration__lt='YYYY-MM-DD')

Consider I have a Product modal with the field created

class Product(models.Model):
     created = models.DateTimeField(auto_now_add=True)
     #other fields

Product.objects.filter(created__lt='2019-05-15')

Upvotes: 0

Artyom Tsoy
Artyom Tsoy

Reputation: 2238

Like Ivan Starostin mentioned in comment F expressions are very useful:

today = datetime.now()
plans = Plan.objects.filter(date__lt=today - F('duration'))

Upvotes: 2

Related Questions