[Django]-Django queryset return DurationField value in seconds

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()

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")
👤kadewu

Leave a comment