简体   繁体   中英

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?

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM