Hi I want to start a background thread that runs the first time my Application is running. I have implemeted it using the ready()
function of the application config.
class MyappConfig(AppConfig):
name = 'myApp'
def ready(self):
try:
thread = threading.Thread(target=xxxx)
except:
pass
Problem is this method is called when Django runs its migrations as well, which it should not. How can I prevent this from happening.
I have tried using Django background tasks but it simply wont run the task at all
you can either: temporarily remove your migration, execute python manage.py migrate, add again your migration and re-execute python manage.py migrate. Use this case if the migrations refer to different models and you want different migration files for each one of them.
Django writes a record into the table django_migrations consisting of some information like the app the migration belongs to, the name of the migration, and the date it was applied.
You should think of migrations as a version control system for your database schema. makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database.
You can selectively disable migration for one or more Django-Models by setting managed = False in Django Model Meta options. Save this answer.
You can avoid executing code if the script is called with "python manage.py [migrate]":
import sys
if not 'manage.py' in sys.argv:
....
I found the best way to do it was to check if runserver
was in the sys.argv
from django.apps import AppConfig
import sys
class config(AppConfig):
name = 'appName'
if 'runserver' in sys.argv:
do_main_thread()
this works better then manage.py
because the argument is in every command i used to migrate
, makemigrations
and runserver
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With