Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete Django object after countdown?

In the platform I am working on we want users to be able to set expiry times on the objects they create. After the countdown they set expires, that object should be deleted.

How would you recommend doing this?

Edit: I should clarify that the expiry time will vary per object.

like image 213
Programmingjoe Avatar asked Dec 19 '22 03:12

Programmingjoe


2 Answers

The most common way to do what you are describing is to create a column that stores the time of creation and column for the expiry time and simply consider items deleted after the expiry time.

You will have to include a condition in any queries against that table to filter out expired items whenever you intend to retrieve a list of non-expired items.

If it is important to eliminate the data for some reason (like a regulatory one or because it's a business requirement) you can set up a periodic task, like a cron job, to delete any records which are expired. This could be (and often is) used in conjunction with the approach I described above, so that you can be confident users are seeing correct data even if some objects have expired since the last time the periodic task was run.

like image 146
Jiaaro Avatar answered Dec 20 '22 17:12

Jiaaro


Jiaaro is exactly right: instead of relying on deleting it exactly at the right time, you should store the date of creation inside of the model, and then override the default QuerySet for this model. Look here for more information.

A manager is a way of adding/changing search functionality. Overriding get_queryset() changes what you see when you do MyModel.objects.all(). In your case, your manager would look like this:

class MyModelManager(models.Manager):
    def get_queryset(self):
        now = datetime.now()
        min_created_at = #now - 30 minutes
        return super(MyModelManager, self).get_queryset().filter(created_at__gt=min_created_at)

class MyModel(models.Model):
    created_at = models.DateField(auto_now_add=True, db_index=True)
    objects = MyModelManager()

Then, on top of that, you could intermittently use a cronjob to clear out stale data. Mauricio's link shows how to do that if you're interested. That won't change the end result, but could keep your queries a bit faster.

like image 43
Sam Bobel Avatar answered Dec 20 '22 17:12

Sam Bobel