Making queries using F() and timedelta at django

前端 未结 4 1654
借酒劲吻你
借酒劲吻你 2020-12-11 16:06

I have the following model:

class Process(models.Model):
  title = models.Charfield(max_length=255)
  date_up = models.DateTimeField(auto_now_add=True)
  day         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 17:04

    I tried to use solution by Lutz Prechelt above, but got MySQL syntax error. It's because we can't perform arithmetic operations with INTERVAL in MySQL.

    So, for MySQL my solution is create a custom DB function:

    class MysqlSubDate(Func):
        function = 'SUBDATE'
        output_field = DateField()
    

    Example of usage:

    .annotate(remainded_days=MysqlSubDate('end_datetime', F('days_activation')))
    

    Also you can use timedelta, it will be converted into INTERVAL

    .annotate(remainded_days=MysqlSubDate('end_datetime', datetime.timedelta(days=10)))
    

提交回复
热议问题