How would you iterate through a table, using the Django ORM, and test the datetime fields to see if they are 8 days old, then delete them if they True.
# models.py
from django.db import models
class Tweet(models.Model):
tweet_id = models.Charfield()
tweet_date = models.DatetimeField()
# tasks.py
from celery import shared_task
from datetime import datetime, timedelta
@shared_task(name='cleanup')
def cleanup():
tweets = MyModel.objects.all()
for tweet.tweet_date in tweets:
if tweets.tweet_date <= datetime.now() - timedelta(days=8):
# remove this record from the table
You can directly query the database for more than 8 days old tweets
using lte
and delete the resultant tweets
. There is no need of iterating over the results and then individually deleting all of them.
@shared_task(name='cleanup')
def cleanup():
# filter and delete more than 8 days old tweets
Tweet.objects.filter(tweet_date__lte=datetime.now()-timedelta(days=8)).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.