Datetime differences in Django using SQLite

前端 未结 1 373
攒了一身酷
攒了一身酷 2021-01-14 15:58

I\'m creating a Django app that needs to perform date differences. Given a model with a start_date and end_date, both DateFields, on P

相关标签:
1条回答
  • 2021-01-14 16:48

    I actually got around this by making a custom database function that only does anything on SQLite, like that below:

    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)
    

    Then, used an ExpressionWrapper in the code to coerce the difference into a DurationField (note this only works in Django 1.8)

    ExpressionWrapper(db.ForceDate(F(a))-db.ForceDate(F(b)), output_field=DurationField())
    
    0 讨论(0)
提交回复
热议问题