In my program, I have scheduled a task that is aimed at changing the status of insurance to Expiré if the due date is equal to the current date when I run the program. The script supposes to loop up throughout the Contract's table and fetches the rows that are corresponding to the condition we used in the script. However, it is changing the status of the whole table including rows that should not be affected by the imposed condition. Here is the jobs.py file that is scheduling the task of changing the status of the insurance to Expiré if the condition is true.
from assurance_auto.models import Contrat
from datetime import datetime, timedelta,date
from django.conf import settings
def status_schedule():
contractList = Contrat.objects.all()
for contrat in contractList:
if contrat.get_NbDays()<=date.today() and contrat.statut_assurance=='Encours':
contractList.update(statut_assurance='Expiré')
print('Numéro de contrat est :',contrat.numero_de_contrat,\
' et le statut est: ',contrat.statut_assurance)
else:
break
Below is the updater.py file. This function is about scheduling the execution time of the job
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from .jobs import status_schedule
def start():
scheduler = BackgroundScheduler()
scheduler.add_job(status_schedule, 'interval', seconds=5)
scheduler.start()
In the apps.py file, I have the program below which consists of running the updater file once the program is running.
from django.apps import AppConfig
class AssuranceAutoConfig(AppConfig):
name = 'assurance_auto'
def ready(self):
from jobs import updater
updater.start()
The two circled rows are the ones supposed to change the status to Expiré. However, all rows are changing the status to Expiré which is not what I want to get as a result. How can I solve this programming error, please?
CodePudding user response:
contractList = Contrat.objects.all()
for contrat in contractList:
if contrat.NbDays<=date.today() and contrat.statut_assurance=='Encours':
Contrat.objects.filter(id=contract.id).update(statut_assurance='Expiré')
print('Numéro de contrat est :',contrat.numero_de_contrat,\
' et le statut est: ',contrat.statut_assurance)
CodePudding user response:
You should not update the contractList
, since that is a queryset with all records, you update that item with:
def status_schedule():
for contrat in Contrat.objects.filter(statut_assurance='Encours'):
if contrat.get_NbDays() <= date.today():
contrat.statut_assurance = 'Expiré'
contrat.save()
print('Numéro de contrat est :',contrat.numero_de_contrat,\
' et le statut est: ',contrat.statut_assurance)
You should also not break
the loop.
Depending on the implementation of get_NbDays
, you can also move that to the .filter(…)
clause and in that case work with a .update(…)