如何在django中以一定的时间间隔获取所有对象

How to get all objects with certain interval of time in django

我想用 django python ORM 获取所有有时间在接下来的 5 秒内存活的对象。我正在尝试以下方式,但我不知道为什么它不起作用或我做错了什么...

queryset.py

def ttl_expire_list(self):
        query = self.filter(is_remove=False,ttl__range=[timezone.now() + timedelta(seconds=5), timezone.now()]).order_by("-ttl")
        # query = self.filter(is_remove=False).order_by("-ttl")
        return query'

models.py

class Notification(models.Model):

    sender = models.CharField(_("Sender"), max_length=100,null=True,blank=True)

    receiver = models.CharField(_("Receiver"), max_length=100,null=True,blank=True)
    message = models.TextField(_("Message"),null=True,blank=True)

    is_read = models.BooleanField(_("Read") ,default=False,null=True,blank=True)
    ttl = models.DateTimeField(_("Time to live"),null=True,blank=True) 
    create_time = models.DateTimeField(_("Created Time"), default = timezone.now)

解决方案

def ttl_expire_list(self):
        print("curen",timezone.now()) 
        print("imte :",timezone.now() + timedelta(seconds=5))
        query = self.filter(is_remove=False,ttl__range=(timezone.now() , timezone.now()+timedelta(seconds=50))).order_by("-ttl")
        return query

range 的第一个参数应该是开始日期,然后是结束日期,只需交换参数即可:

ttl__range=[timezone.now(), timezone.now() + timedelta(seconds=5)]