Home > Mobile >  Django model auto update status when the medicine is expired
Django model auto update status when the medicine is expired

Time:08-21

How to Auto update the status when the medicine is expired? for example, I created medicine record and set the expirationdate to july 2022, if the current date is greater than the expirationdate it will update the status of medicine to "Expired", How do I do that?

class Medicine(models.Model):
    medstatus = [
        ("Expired", "Expired"),
        ("Active", "Active")
    ]
    description = models.CharField(max_length=50, null=True)
    expirationDate = models.DateField(null=True)
    status = models.CharField(max_length=50, choices=medstatus,  null=True)

CodePudding user response:

Create crontab for one time in a day as:

#this is example for each day 00:00 sending get request to you api
0 0 * * * /usr/bin/curl --silent http://example.com/your_views_url/ &>/dev/null

This is good and easy to understand cronjob generator:

https://crontab.guru/#0_0_*_*_*

Cronjob will trigger a view, which will search for a medicine, and change its status:

urls.py:

path("your_views_url", views.your_view_name_here),

views.py:

from django.http import HttpResponse
from datetime import datetime

def your_view_name_here(request):
    now = datetime.today()
    
    #this will return a queryset of all medecine which you need to change status
    all_target_medecine = Medicine.objects.filter(medstatus = "Active", expirationDate__lt = now)

    for medecine in all_target_medecine:
        medecine.medstatus = "Expired"
        medecine.save()
    return HttpResponse("Ok")
  • Related