Erathiian
Erathiian

Reputation: 140

Automatically create django model instances at startup with empty database

My django project requires some model instances to be created at startup if they do not exist.

I currently create the required model instances I need in an app config.

class MyAppConfig(AppConfig):
name = 'my_app'

def ready(self):
    create_required_objects()

def create_required_objects():
    from my_app.models import MyObject
    for name in MyObject.reserved_names:
        if not MyObject.objects.filter(name=name).exists():
            MyObject.objects.create(name=name, not_editable=True)

This works perfectly when the sqlite database is initialized, however if I clear the database and then try to run the sever, I get the following error:

django.db.utils.OperationalError: no such table: my_app_object

I would like to be able to clear the database (preferably by just removing db.sqlite3) and run the server.

Upvotes: 1

Views: 2197

Answers (2)

Gaurav Goyal
Gaurav Goyal

Reputation: 68

Use post_migrate signal to create a new instance when migrating to the new database:

Like:

from django.db.models.signals import post_migrate
from my_app.models import MyObject

def create_required_objects(sender, **kwargs):
    for name in MyObject.reserved_names:
       if not MyObject.objects.filter(name=name).exists():
            MyObject.objects.create(name=name, not_editable=True)
   
class MyAppConfig(AppConfig):
    name = 'my_app'

def ready(self):
    post_migrate.connect(create_required_objects ,sender=self)

    
   

This code automatically generates the user after migrating to the database.

Upvotes: 1

Jun Zhou
Jun Zhou

Reputation: 1117

You can use model_bakery to populate some temp data. You may need to do makemigrations and migrate to set up all tables in your database, you can follow this workflow.

python manage.py makemigrations
python manage.py migrate

In terms of populating data, you can try the following code:

from model_bakery import baker
from my_app.models import MyObject

baker.make(MyObject)

Add baker.make(MyObject) in your create_required_objects function after installation of model_bakery:
pip install model_bakery

Upvotes: 0

Related Questions