Home > OS >  How can I delete a data on db automatically after 24 hours in django?
How can I delete a data on db automatically after 24 hours in django?

Time:02-08

I want to make an instagram clone with django. I'm trying to make stories of instagram on Django Models.As you know, instagrams stories are deleted after 24 hours. How can i delete data from database?

CodePudding user response:

Just filter these out. You can make a model that looks like:

class MyModel(models.Model):
    # …
    timestamp = models.DateTimeField(auto_now_add=True, db_index=True)

then you can retrieve only MyModel objects that are at most 24 hours old with:

from datetime import timedelta
from django.db.models.functions import Now

MyModel.objects.filter(timestamp__gte=Now()-timespan(days=1))

you can occasionally run a management command that removes the old MyModels with:

from datetime import timedelta
from django.db.models.functions import Now

MyModel.objects.filter(timestamp__lt=Now()-timespan(days=1)).delete()
  •  Tags:  
  • Related