Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 582
a_Fraley Avatar asked Jan 21 '26 10:01

a_Fraley


1 Answers

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()
like image 135
Rahul Gupta Avatar answered Jan 23 '26 01:01

Rahul Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!