[Django]-Using Django ORM, Iterate through table records, test them and delete the record if needed

4👍

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

Leave a comment