5分钟后自动删除对象 [英] Delete an object automatically after 5 minutes
问题描述
我正在尝试创建一个在发布5分钟后自动删除对象的功能.
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.
推荐答案
您应该交换比较,所以:
You should swap the comparison, so:
if time < datetime.datetime.now():
# ...
或者更具可读性:
if self.publishing_date < datetime.datetime.now()-datetime.timedelta(minutes=5):
# ...
因为这意味着现在现在前五分钟仍在发布 Event
的时间之后.
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()
然后, Event.objects
将仅检索不到五分钟前发布的 Event
.
Then Event.objects
will only retrieve Event
s 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()
这将删除批量"中的这些 Event
.
This will then remove these Event
s in "bulk".
这篇关于5分钟后自动删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!