django initializes an instance of the database

  • 2020-10-23 20:09:43
  • OfStack

The most recent project needs to initialize 1 bit of data after the table is created. There are many ways to initialize Django data, but all require extra manual manipulation and are not intelligent.

There is one way to initialize the database using the post_syncdb signal, but I used version 1.8 of Django, using python manage.py migrate to synchronize the database, instead of using Python manage.py syncdb to synchronize the database, so I wanted to see if I could use the post_migrate signal to initialize the database. Studied signal of Django, tried 1, and sure enough, it worked.

In your APP directory, create 1 file management.py


from django.db.model.signal import post_migrate
from myapp.models import MyModel

# define receiver function 
def init_db(sender, **kwargs):
 if sender.name == 'MyModel.__name__':
  if not MyModel.objects.exists():
   MyModel.objects.create()  #  When sending a signal to the model you want to initialize the model, in the database operation, without judgment, each 1 All models are called 

post_migrate.connect(init_db)

That's it. Once you execute Python ES28en.py migrate, the data will be initialized.


Related articles: