如何在Django中实现MYSQL的TIMESTAMPDIFF(UNIT,EXPR_1,EXPR_2)
(作为DB函数)?
答案 0 :(得分:1)
我在这里How to annotate a difference of datetime in days回答了类似的问题。
from django.db.models.functions import Func
class TimeStampDiff(Func):
class PrettyStringFormatting(dict):
def __missing__(self, key):
return '%(' + key + ')s'
def __init__(self, *expressions, **extra):
unit = extra.pop('unit', 'day')
self.template = self.template % self.PrettyStringFormatting({"unit": unit})
super().__init__(*expressions, **extra)
function = 'TIMESTAMPDIFF'
template = "%(function)s(%(unit)s, %(expressions)s)"
用法
TimeStampDiff(expr_1,expr_2,unit=valid_unit)