Select record whose datetimefield is older, in minutes, than constant value in related field
I have a Django-based checkout system for an event I run. It has the following models: Game, Checkout.
class Game(models.Model):
name = models.CharField(max_length=100)
playtime = models.IntegerField(null=True, blank=True)
#.. and a few other fields
class Checkout(models.Model):
checked_out = models.DateTimeField(default=now())
returned = models.DateTimeField(null=True, blank=True)
attendee = models.ForeignKey(Attendee, on_delete=models.CASCADE)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
I would like to notify users when they have a Game has not been returned, and has been checked out for longer than 2 X the playtime value
Example:
* Penelope checked out game Cascadia 61 minutes ago.
* The playtime of Cascadia is 30 minutes
* When querying the checkouts table, this record would be returned using the following SQL query:
select c.*,
(strftime('%s', 'now') - strftime('%s', c.checked_out)) / 60 AS elapsed_minutes
from checkout c
inner join game g on c.game_id = g.id
where c.returned IS NULL
and elapsed_minutes > g.playtime * 31
But I'm having trouble creating the Django ORM QuerySet to retrieve the records.
I'm starting with the following, but it's failing with the error unsupported type for timedelta minutes component: CombinedExpression
checkouts = Checkout.objects.filter(returned=None).filter(checked_out__gt=timedelta(minutes=F('game__playtime') + multiplier)))