10👍
✅
Sure can, but the exact mechanism may depend upon your database.
In postgres, you can use EXTRACT(epoch FROM <interval>)
to get the total number of seconds.
To use this in Django, you can create a Func
subclass:
class Epoch(django.db.models.expressions.Func):
template = 'EXTRACT(epoch FROM %(expressions)s)::INTEGER'
output_field = models.IntegerField()
Then you can use it directly:
base_posts.annotate(
response_time_sec=Epoch(F('min_comment_date') - F('date_created'))
)
1👍
Nice solution!
One wrinkle is that I think there is a missing ‘s’ needed to get this to work in Django 3
class Epoch(django.db.models.expressions.Func):
template = 'EXTRACT(epoch FROM %(expressions)s)::INTEGER'
output_field = models.IntegerField()
- [Django]-Using Python 3.7 on Pycharm gives me: "Error: Django is not importable in this environment"
1👍
As already answered here, it depends upon your database. As stated in Django documentation of Extract method:
Django usually uses the databases’ extract function, so you may use any lookup_name that your database supports.
So for example with PostgreSQL:
response_time_in_sec=Extract(F("response_time"), "epoch")
- [Django]-ElasticSearch term suggest on analyzed field returns no suggestions
- [Django]-Kubernetes liveness probe fails when the logs show a 200 response
- [Django]-Couldn't import Django error when I try to startapp
- [Django]-What do I need to run Sentry inside my django site
- [Django]-Django Social Auth w/ Twitter: HTTP 401 Error (Unauthorized)
Source:stackexchange.com