Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading