Opened 4 years ago

Closed 4 years ago

#31658 closed New feature (wontfix)

Performing SQL queries in AppConfig.ready().

Reported by: Ying Wang Owned by: nobody
Component: Core (Other) Version: 3.0
Severity: Normal Keywords: database, migrations, lifecycle, hooks
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello,

I might have an unusual request for understanding Django lifecycle methods. I would like to run an SQL query during application startup in order to configure PostgreSQL triggers and functions. Right now, my understanding is Django can load custom AppConfigs and overwrite method 'ready()' with custom logic. However, this AppConfig is run all the time, including during all commands of 'manage.py', which means 'manage.py migrate' cannot be run without first hitting the custom AppConfig. This means my SQL file errors out, since the underlying PostgreSQL tables do not yet exist and I cannot even make a hardcoded reference to them. So I have to check whether or not the database is synchronized with the application, before running the SQL script. I don't want to execute the migration during the AppConfig ready() step, since there may be other commands I want to run in some specific order, and I see it as more of a CLI command. So my other option would then be to run 'manage.py' multiple times, and only run the SQL file once the database is synchronized. This may make ops overhead a bit more complicated.

I think having multiple handles, like 'DatabaseHasSynchronized()', and external stateful hooks critical to Django usage, as top-level AppConfig overriddable methods would be really useful in managing app lifecycles. That way, less stuff needs to be done using the shell. This might be like React.js's 'ComponentDidMount()' or 'ComponentWillMount()' lifecycle methods where you have high API-level visibility into lifecycles.

I'm not sure if it's a good idea, so I wanted to raise it as a topic of discussion. I'd be happy to take a shot at implementing this, should the feature be deemed by the community as worthwhile.

Thanks
Ying

Change History (1)

comment:1 by Mariusz Felisiak, 4 years ago

Component: MigrationsCore (Other)
Resolution: wontfix
Status: newclosed
Summary: [POSSIBLE FEATURE REQUEST] Additional Django lifecycle methods?Performing SQL queries in AppConfig.ready().

Database operations shouldn't be performed at module loading time, you can find a warning in AppConfig.ready() docs (see related #30424). We don't want to encourage user to do this.

Note: See TracTickets for help on using tickets.
Back to Top