I’m trying to create a django query that compares my models created_at
date to see if they are at least x hours old where x is defined in a nested JsonField hours_old
.
So for example:
# This creates a timedelta ("Duration" natively, I think)
hours_past = ExpressionWrapper(
timezone.now() - F('created_at'),
output_field=DateTimeField()
)
Person.objects.annotate(
hours_old=F('settings__json__data__hours_old') # Let's say this is an int of 3
hours_past=hours_past # Let's say this is a timedelta of 2 days
).filter(
hours_old__lt=F('hours_past') # I want 3 < 48
)
But I can’t compare a time duration to a random int obviously. What’s the play here?
Using django==3.2.5
2
Answers
Got it! Thanks to Zegarek and lxop for the inspiration!
Seems casting
timedelta
toDateTimeField
creates aDurationField
. The json was being turned into an int after the query ran, but not during. Comparisons and math were failing until I cast it to anIntegerField
manually.If
created_at
is a timestamp,hours_past
results in atimedelta
/interval
and itsoutput_field
should be aDurationField()
instead:For your filter, you can convert one:
Or the other