0

I am trying to convert a decimal value from my Django model into a time format of MM:SS:MS.

For example: 97.13 as a decimal value would become 01:37:13.

Is there any easy way to implement this with a raw SQL query in Django? Lets say I have this raw query:

example = Example.objects.raw("""SELECT x.id, x.time FROM your_Table x WHERE x.id = %s""", [id])

Would it be better to execute the raw query and manipulate it in Python? How would I go about that? Could I loop the values e.g.?

for examples in example:
    formatted_time = function(examples.time)

Ultimately I'd like to pass my example object (with converted time) to my template.

Thanks in advance.

Zakerias
  • 356
  • 2
  • 3
  • 18

1 Answers1

1

One approach would be to use Django's "Template Filters" and make a template filter for that conversion.

https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/

It would look something like:

@register.filter
def decimal_to_time_filter(decimal_value):

   # implement this conversion
   result = convert decimal_value to hh:mm:ss format

   return result

In your template you would display the reformatted data by using your custom 'decimal_to_time_filter' filter.

{{ your_decimal_field|decimal_to_time_filter }}

mmccaff
  • 1,281
  • 1
  • 11
  • 20
  • Thank you, this is exactly what I was looking for. A have a version up and running although the function itself requires some work. – Zakerias Jul 31 '18 at 10:46