Home > Net >  Can you make an objects that deletes itself in Django?
Can you make an objects that deletes itself in Django?

Time:02-10

So I made model VerificationToken

class VerificationToken(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    code = models.CharField(max_length=4)
    date_created = models.DateTimeField(auto_now_add=True)


    @property
    def expiration(self):

        lifetime = timedelta(minutes=10)

        expire = self.date_created   lifetime

        return expire

and this model have an expiration property. Is there a way to make this model delete itself after it expires?

CodePudding user response:

I believe that Django does't provide that kind of functionality. You can use Celery to create a celery task that will delete tokens that expires after certain amount of time. Also you can create task that will periodically find expired tokens and will delete them.

Celery documentation

CodePudding user response:

Unfortunately it's not possible. What you can do is to create a cronjob using celery-beat or what you like and set a cronjob task to clean up expired DB records (once per minute/hour/day)

CodePudding user response:

Just make a filter that prevents retrieving expired VerificationTokens:

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

VerificationToken.objects.filter(
    date_created__gte=Now()-timedelta(minutes=10)
)

You can also make a manager such that VerificationToken.objects is a manager that only contains non-expired tokens:

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

class VerificationTokenManager(models.Manager):
    
    def get_queryset(self):
        return super().get_querset().filter(
            date_created__gte=Now()-timedelta(minutes=10)
        )

class VerificationToken(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    code = models.CharField(max_length=4)
    date_created = models.DateTimeField(auto_now_add=True, db_index=True)
    objects = VerificationTokenManager()

you can then make a management command [Django-doc] that you for example run through cron, or some other scheduling task that removes expired VerificationTokens with:

# app_name/management/commands/remove_expired_tokens.py

from datetime import timedelta
from django.core.management.base import BaseCommand
from django.db.models.functions import Now
from app_name.models import VerificationToken

class Command(BaseCommand):
    help = 'Remove expired verification tokens'

    def handle(self, *args, **options):
        VerificationToken._base_manager.filter(
            date_created__lt=Now()-timedelta(minutes=10)
        ).delete()

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

  • Related