Best way to delete a django model instance after a certain date

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

I am writing a little app where the user creates an event and specifies the date that event will occur. After the event date has past, I want to delete that event instance. My current attempt is throwing a function that checks if the event should expire in the event page view. I am not sure whether the expiration_check function is checking in a correct way, nor am I sure whether just having a function in the view will event work.

Here is my view and expire function:

def event_page(request, name):     event = Event.objects.get(name=name)      check_expiration(event)      if request.method == "POST":         form = GuestForm(request.POST)         if form.is_valid():             Guest = form.save(commit=False)             Guest.event = event             Guest.save()             return redirect(event)     else:         form = GuestForm()         return render(request, "event_page.html", {"form": form, "event": event, })   def check_expiration(event):     now = datetime.datetime.now()      if event.date 

I collect the date from the user and store it in a DateTime filed: date = models.DateField()

Let me know if any further details are needed. Any insight is appreciated, thanks!

回答1:

If you're hosting your application on a UNIX platform (GNU/Linux, OSX, etc.), it's probably best to make use of cron, the generic system utility for running things periodically.

This requires implementing your expiry code as a custom management command:

  1. If you don't have any custom management commands already, create the following directory structure:

    yourapp/   management/      __init__.py (blank)      commands/        __init__.py (blank)        expire_events.py 
  2. In expire_events.py, create a new class along the lines of the following:

    from django.core.management.base import NoArgsCommand  class Command(NoArgsCommand):      help = 'Expires event objects which are out-of-date'      def handle_noargs(self):         print Event.objects.filter(date__lt=datetime.datetime.now()).delete() 
  3. Now you should be able to run ./manage.py expire_events and have any events with expiry dates in the past deleted.

To run this at regular intervals using cron (these instructions are for GNU/Linux but may well work on other UNIX variants), run sudo crontab -e and add the following line:

*/5 * * * * /path/to/your/django/app/manage.py expire_events 

(this would run the task every 5 minutes; see the crontab documentation for advice on specifying job run times)



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