Home > Mobile >  Django save model everyday
Django save model everyday

Time:05-10

I have a model and a signal in models.py and this model sends message to discord webhook with how many days left to something. I want to refresh it everyday at 12:00 AM everyday automatically without using django-celery cause it doesnt work for me. My plan is do something like this

time_set = 12

if time_set == timezone.now().hour:
   ...save model instances...

but i have totally no idea how to do it And i want to do it this way cause when model instance are saved signal runs

CodePudding user response:

Django doesn't handle this scenario out of the box, hence the need for celery and its ilk. The simplest way is to set a scheduled task on the operating system that calls a custom django management command (which is essentially a python script that can reference your django models and methods etc by calling python manage.py myNewCommand).

You can find more about custom commands at https://docs.djangoproject.com/en/4.0/howto/custom-management-commands/

CodePudding user response:

You can create a custom management command and call it by using a cron entry, set to run every day.

Check Django official documentation for the instructions on creating the custom command.

Instead of calling the save() method each time, I'd create a send_discord_message() on the model, and call it wherever required. If you need to execute it every time an instance is saved, then is preferred to use an override save() method in the model. Signals are a great way to plug and extend different apps together, but they have some caveats and it is simpler to override the save() method.

I'm supposing you are using a Unix-like system. You can check how to configure and create cron jobs.

  • Related