Reputation: 5599
I have a ticket model. I need to list out the tickets that are from a specific show, also which has been either bought or the time difference between now and booked_at
is less than 5 minutes.
class Ticket(models.Model):
show = models.ForeignKey(Show)
seat = models.ForeignKey(Seat)
user = models.ForeignKey(User)
booked_at = models.DateTimeField(default=timezone.now)
bought = models.BooleanField(default=False)
unavailable = Ticket.objects.filter(show=show).filter(Q(bought=True) | Q(booked_at = ????))
How can I query for the difference between now
and the booked_at
field to check if its less/more than X minute?
Upvotes: 1
Views: 816
Reputation:
The __range
lookup can be used to select model instances within a specified range, including dates and times.
Combine that with datetime.timedelta
and you can pretty much write all you need:
from django.utils import timezone
from datetime import timedelta
within_5_minutes = timezone.now() - timedelta(seconds=300)
unavailable = Ticket.objects.filter(
show=show
).filter(
Q(bought=True) | Q(booked_at__range=(within_5_minutes, timezone.now())
)
Upvotes: 2
Reputation: 21
You can try the following:
import datetime
booked_at__gt=datetime.datetime.now()-datetime.timedelta(minutes=5)
Upvotes: 2