Delete an object automatically after specified time

Viewed 723

Trying to delete an object after a specified time from the database.

Here's my Code:

from datetime import timedelta
from django.db import models
from django.utils.timezone import now

class Email(models.Model):
    email = models.EmailField(max_length=256)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return 'code: ' + str(self.code)

    @property
    def deletes_in_ten_seconds(self):
        time = self.created_at + timedelta(seconds=10)
        query = Email.objects.get(pk=self.pk)
        if time > now():
            query.delete()

Yet it's not working. Do I have to call the delete method after a while somehow? I really don't have a clue. (new to django)

3 Answers

First of all deletes_in_ten_seconds() isn't ever called in your code, so the query isn't ever going to run.

Secondly, yes, you have to ask the database to delete your rows when it needs to happen, so you're going to need to schedule this (every so often) somehow. There are many ways to do it: from threads inside your python app to using functionality provided by the database.

from datetime import timedelta
from django.db import models
from django.utils.timezone import now

class Email(models.Model):
    email = models.EmailField(max_length=256)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return 'code: ' + str(self.code)

    @property
    def deletes_in_ten_seconds(self):
        time = self.created_at + timedelta(seconds=10)
        query = Email.objects.get(pk=self.pk)
        
        # add this code
        while True:
           if time > now():
              query.delete()
              break

When deletes_in_ten_seconds is executed, the if statement is not satisfied and therefore it exits without further judgment. So you must add a while loop, to keep it running until query.delete() occurs.

Related