Search code examples
pythondjangoorm

Deleting items autometically after 15 days of creation from database in django


To achieve this functionality i have used Django Signals, but that is not working in my case, Please let me know if i have done this right, You can also suggest me any other way to achieve this functionality

signals.py

from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils import timezone
from smart_search.models import UserHitCount

@receiver(pre_delete, sender=UserHitCount)
def delete_user_hit_count(sender, instance, **kwargs):
    print("signal handler triggered!")
    if timezone.now() - instance.created_at > timezone.timedelta(minutes=1):
        instance.user.delete()

app.py

from django.apps import AppConfig

class SmartSearchConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'smart_search'

    def ready(self):
        from . import signals

init.py

default_app_config = 'smart_app.apps.SmartAppConfig'

model.py

from django.db import models
from user_application.models import Registered_user

class UserHitCount(models.Model):
    user = models.OneToOneField(Registered_user, on_delete=models.CASCADE)
    search_count = models.IntegerField(default=0)
    question_count = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True, null=True)

My main objective is to delete the things once created date is less then today and this should be done automatically


Solution

  • You need to look into cronjobs or background tasks queue. For example Celery: https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html

    Create a periodic task that will run every day or every hour and check if there are records that should be deleted;

    Example:

    @shared_task
    def example_task():
        UserModel.objects.filter(created_at__lte = now() - timedelta(days=15)).delete()