Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django run code on application start but not on migrations

Tags:

python

django

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

like image 918
Dhanushka Amarakoon Avatar asked Jun 20 '16 06:06

Dhanushka Amarakoon


People also ask

How do I fix migration issues in Django?

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.

How does Django know which migrations have run?

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.

What is difference between migration and migrate in Django?

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.

How do I stop migrations in Django?

You can selectively disable migration for one or more Django-Models by setting managed = False in Django Model Meta options. Save this answer.


2 Answers

You can avoid executing code if the script is called with "python manage.py [migrate]":

import sys
if not 'manage.py' in sys.argv:
    ....
like image 72
JulienD Avatar answered Oct 19 '22 21:10

JulienD


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.

like image 2
mmartin Avatar answered Oct 19 '22 20:10

mmartin