How to delete all records which is 24 hours old using django ORM?

Question:

Model:

class Question(models.Model):
    question_text = models.CharField(max_length=100)
    option1 = models.CharField(max_length=50,null=False)
    option1_vote = models.IntegerField(default=0)
    option2 = models.CharField(max_length=50,null=False)
    option2_vote = models.IntegerField(default=0)
    option3 = models.CharField(max_length=50,null=False)
    option3_vote = models.IntegerField(default=0)
    option4 = models.CharField(max_length=50,null=False)
    option4_vote = models.IntegerField(default=0)
    date_time = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User,on_delete=models.CASCADE)

We have the date_time field here.

Question.objects.filter(condition).delete()

what condition should I put there?

Asked By: Amol_G

||

Answers:

You can use Python timedelta.

from datetime import datetime, timedelta
last_24h = datetime.now() - timedelta(hours=24)

Question.objects.filter(date_time__lte=last24h).delete()
Answered By: shafik

You can use timedelta() and Now() from functions library.

Try this:

from datetime import timedelta
from django.db.models.functions import Now

Question.objects.filter(date_time__lte=Now()-timedelta(days=1)).delete()
Answered By: Sunderam Dubey