Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when the database is ready in Django?

I need to do stuff as soon as the database is ready in Django. Specifically, I need to perform some calculations on values from db and fill the results into cache.

Since django 1.7, the application registry makes it easy to know when an app or models are ready to be used. You can write:

from django.apps import apps

if apps.ready:
    do_some_stuff()

But I found out that the models being ready does not mean the database can be queried. Django doc's says:

Although you can access model classes as described above, avoid interacting with the database in your ready() implementation

I tried to hook up to the post_migrate event. It works if I'm rebuilding the database (e.g launching the test suite), but does not if I'm just using an existing db (e.g using runserver).

Is there a way to know if the database is fully available in Django >= 1.7?

like image 205
Thibault J Avatar asked Nov 09 '22 07:11

Thibault J


2 Answers

I use also the post_migrate signal. (as : https://github.com/mrjmad/django_badgificator/blob/master/badgificator/apps.py).

I realize by reading your question it does not work with 'runserver' ...

like image 116
Mr Jmad Avatar answered Nov 15 '22 05:11

Mr Jmad


You can try hooking up a receiver for the connection_created signal.

like image 42
schillingt Avatar answered Nov 15 '22 07:11

schillingt