The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Using Django Orm, Iterate Through Table Records, Test Them And Delete The Record If Needed
00:27 Accepted Answer Score 4
00:45 Thank you

--

Full question
https://stackoverflow.com/questions/3799...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #datetime #orm #celery

#avk47



ACCEPTED ANSWER

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