How to get all objects with certain interval of time in django?
Question:
I am attempting to retrieve all objects with a time-to-live of less than 5 seconds using Django’s ORM in Python. However, my current approach is not producing the expected results. Can you help me understand what I am doing wrong and how I can correctly retrieve these objects?
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)
Solution
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
Answers:
First argument of range should be start date and then end date just swap the arguments:
ttl__range=[timezone.now(), timezone.now() + timedelta(seconds=5)]
I am attempting to retrieve all objects with a time-to-live of less than 5 seconds using Django’s ORM in Python. However, my current approach is not producing the expected results. Can you help me understand what I am doing wrong and how I can correctly retrieve these objects?
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)
Solution
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
First argument of range should be start date and then end date just swap the arguments:
ttl__range=[timezone.now(), timezone.now() + timedelta(seconds=5)]