1

I have the following model:

class Ticket(models.Model):
    # ... other fields omitted
    active_at = models.DateTimeField()
    duration = models.DurationField()

Given now = datetime.now(), I'd like to retrieve all records for which now is between active_at and active_at + duration.

I'm using Django 1.8. Here are the DurationField docs.

Johnny 5
  • 1,521
  • 3
  • 10
  • 11
  • 1
    Have you looked at [F objects](https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model)? – xnx Mar 15 '15 at 00:06

1 Answers1

3

As noted in the documentation, arithmetic with a DurationField will not always work as expected in databases other than PostgreSQL. I don't know to which extend this works or doesn't work in other databases, so you'll have to try it yourself.

If that works, you can use the following query:

from django.db.models import F

active_tickets = Ticket.objects.filter(active_at__lte=now, 
                                       active_at__gt=now-F('duration'))

The F object refers to a field in the database, duration in this case.

knbk
  • 52,111
  • 9
  • 124
  • 122