当前位置:首页 > 数据库 > SQlite

python-使用SQLite的Django中的日期时间差异

我正在创建一个需要执行日期差异的Django应用.给定一个具有start_date和end_date的模型,在Postgres上的两个DateFields都可以像以下命令一样工作:

model.objects.annotate(difference=F(end_date)-F(start_date))

会很好地工作.但是,在SQLite后端上,此方法也不起作用.

它没有给出时间增量(或类似时间),而是返回一个字符串,该字符串大约是几年之间的差值.但是,SQLite具有命令julianday(),它将日期转换为“ julian day”,该日期至少可以用来获得天数差异.

例如,在dbshel??l上,这将给出正确的天数差异:

SELECT julianday(end_date) - julianday(start_date) FROM 'appname'.'model'; 

有什么办法可以:

>检查数据库后端-例如.是SQLite吗?
>,然后,如果是SQLite,则将其包装在julianday函数中?

解决方法:

我实际上是通过制作一个仅在SQLite上执行任何操作的自定义数据库函数来解决的,如下所示:

from django.db.models.expressions import Func
# SQLite function to force a date time subtraction to come out correctly.
# This just returns the expression on every other database backend.
class ForceDate(Func):
    function = ''
    template = "%(expressions)s"
    def __init__(self, expression, **extra):
        self.__expression = expression
        super(ForceDate, self).__init__(expression, **extra)

    def as_sqlite(self, compiler, connection):
        self.function = 'julianday'
        self.template = 'coalesce(%(function)s(%(expressions)s),julianday())*24*60*60*1000*1000' # Convert julian day to microseconds as used by Django DurationField
        return super(ForceDate, self).as_sql(compiler, connection)

然后,在代码中使用ExpressionWrapper将差异强制转换为DurationField(请注意,这仅在Django 1.8中有效)

ExpressionWrapper(db.ForceDate(F(a))-db.ForceDate(F(b)), output_field=DurationField())

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!