Delete an object automatically after 5 minutes

别来无恙 提交于 2021-02-19 16:05:06

问题


I'm trying to create a function that automatically delete an object after 5 minutes from publication.

from django.contrib.gis.db import models
from django.utils import timezone

import datetime

class Event(models.Model):
    name = models.CharField(
        max_length=100,
        )
    publishing_date = models.DateTimeField(
    default=timezone.now,
    blank=True,
    )

    @property
    def delete_after_five_minutes(self):
        time = self.publishing_date + datetime.timedelta(minutes=5)
        if time > datetime.datetime.now():
            e = Event.objects.get(pk=self.pk)
            e.delete()
            return True
        else:
            return False

The problem is that all objects are deleted and not only the objects that I wish.


回答1:


You should swap the comparison, so:

if time < datetime.datetime.now():
    # ...

or perhaps more readable:

if self.publishing_date < datetime.datetime.now()-datetime.timedelta(minutes=5):
    # ...

since this thus means that five minutes before now is still after the time when the Event was published.

That being said, it might be better not to delete the values, or at least not immediately, but make a manager, that simply "hides" these objects. You can then later, periodically, remove the elements.

We can make such manager with:

from django.utils import timezone

class EventManager(models.Manager):

    def get_queryset(self):
        return super().get_queryset().filter(
            publishing_date__gte=timezone.now()-timezone.timedelta(minutes=5)
        )

and then use this manager like:

class Event(models.Model):
    # ...
    objects = EventManager()

Then Event.objects will only retrieve Events that have been published less than five minutes ago.

You can periodically remove such events with:

Event._base_manager.filter(
    publishing_date__lt=timezone.now()-timezone.timedelta(minutes=5)
).delete()

This will then remove these Events in "bulk".



来源:https://stackoverflow.com/questions/57267862/delete-an-object-automatically-after-5-minutes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!