将小数转换为 MM:SS:MS Django
Convert Decimal to MM:SS:MS Django
我正在尝试将我的 Django 模型中的十进制值转换为 MM:SS:MS 的时间格式。
例如:97.13 作为十进制值将变为 01:37:13。
有什么简单的方法可以在 Django 中使用原始 SQL 查询来实现吗?假设我有这个原始查询:
example = Example.objects.raw("""SELECT x.id, x.time FROM your_Table x WHERE x.id = %s""", [id])
在 Python 中执行原始查询并对其进行操作会更好吗?我该怎么做?我可以循环这些值吗?
for examples in example:
formatted_time = function(examples.time)
最终我想将我的示例对象(带有转换时间)传递到我的模板。
提前致谢。
一种方法是使用 Django 的 "Template Filters" 并为该转换创建一个模板过滤器。
https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
它看起来像:
@register.filter
def decimal_to_time_filter(decimal_value):
# implement this conversion
result = convert decimal_value to hh:mm:ss format
return result
在您的模板中,您将使用自定义 'decimal_to_time_filter' 过滤器显示重新格式化的数据。
{{ your_decimal_field|decimal_to_time_filter }}
我正在尝试将我的 Django 模型中的十进制值转换为 MM:SS:MS 的时间格式。
例如:97.13 作为十进制值将变为 01:37:13。
有什么简单的方法可以在 Django 中使用原始 SQL 查询来实现吗?假设我有这个原始查询:
example = Example.objects.raw("""SELECT x.id, x.time FROM your_Table x WHERE x.id = %s""", [id])
在 Python 中执行原始查询并对其进行操作会更好吗?我该怎么做?我可以循环这些值吗?
for examples in example:
formatted_time = function(examples.time)
最终我想将我的示例对象(带有转换时间)传递到我的模板。
提前致谢。
一种方法是使用 Django 的 "Template Filters" 并为该转换创建一个模板过滤器。
https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
它看起来像:
@register.filter
def decimal_to_time_filter(decimal_value):
# implement this conversion
result = convert decimal_value to hh:mm:ss format
return result
在您的模板中,您将使用自定义 'decimal_to_time_filter' 过滤器显示重新格式化的数据。
{{ your_decimal_field|decimal_to_time_filter }}