Search code examples
pythondjangodjango-querysettimedeltadjango-aggregation

Using Django, how I can achieve this in a single query?


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.


Solution

  • 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.