问题
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 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()
This will then remove these Event
s in "bulk".
来源:https://stackoverflow.com/questions/57267862/delete-an-object-automatically-after-5-minutes