Django model auto update status when the medicine is expired

Question:

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)
Asked By: Claire Ann Vargas

||

Answers:

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")
Answered By: oruchkin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.