Making queries using F() and timedelta at django

前端 未结 4 1656
借酒劲吻你
借酒劲吻你 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 16:54

    7 days == 1 day * 7

    F is deep-black Django magic and the objects that encounter it must belong to the appropriate magical circles to handle it.

    In your case, django.db.models.query.filter knows about F, but datetime.timedelta does not. Therefore, you need to keep the F out of the timedelta argument list. Fortunately, multiplication of timedelta * int is supported by F, so the following can work:

    Process.objects.filter(date_up__lte=datetime.now()-timedelta(days=1)*F('days_activation'))
    

    As it turns out, this will work with PostgreSQL, but will not work with SQlite (for which Django 1.11 only supports + and - for timedelta, perhaps because of a corresponding SQlite limitation).

提交回复
热议问题