How to automatically create model instances during boot-up?

Hi,

refering to this old question: What is this warning for AppConfig.ready() about?

Where am I supposed to put my code, that does automatically create some instances from certain models during boot-up time? I was careful and made sure these specific instances do not exist before creating them. Therefore the only query that gets executed during every boot-up is the exists() query.

I’m curious - what exactly is your use-case or need for this?

I’m trying to understand why you might need to test this for each of n-number of worker processes that start or restart at arbitrary times, but is not necessary across a span of days when the service isn’t restarted.

In the general case, you would usually create a data migration to ensure certain models are populated before the application is started.

This is not a hard reference. We don’t have the exact same use-case like in this old question.

In our case we need these specific instances for fallback reasons. For example:
We’re creating queries for another timeseries database. These queries are created automatically from certain elements that the user clicked on the front end.
For this timeseries database ( Influx DB ) you need a set of databases & tables. The user may create it’s own custom ones, but there is a certain set of mandatory ones that you will always need, therefore I’m always asking on every boot up:

  • Do these databases/tables exist?
  • Create them, if not!

I would implement this as a “precursor script” to be run immediately before you launch gunicorn, uwsgi, or what ever you’re using to run your Django service. For example, if you’re starting this in a systemd service file, you could run this as an ExecStartPre command. Or, this could be another command in your init script.

Unless you’ve got reason to believe that this data is going to be deleted while the system is up and running, there’s no reason to do this within the context of your operational Django environment.

Hmm…, there is one reason: It is comfortable.

If I do this within the Django Framework I have not to worry about changing database/table names. May it be in some day that we decide this default table should have another name, or may it be that Django decides to change it’s naming convention, or anything else…

With this approach i have now several scripts, that i have to keep up-to-date synchronously, meaning these scripts and the default tables that are simple Python Enums, have to be same.

That’s the reason why i did this in the first place?

If you create this as a custom Django management command, then it’s part of your project and not something separate for you to manage. It simply moves the code that you’re trying to put into your App file into a command file.

Ah ok, I misinterpreted the words: “precursor script”. I thought you want to run some bare bone SQL here.

OK yes, an admin command would be acceptable I think.

Thanks