Skip to content

Instantly share code, notes, and snippets.

@niwinz
Created July 29, 2012 12:02
Show Gist options
  • Save niwinz/3198204 to your computer and use it in GitHub Desktop.
Save niwinz/3198204 to your computer and use it in GitHub Desktop.
Django model hooks

Django Model Hooks (prototype)

System hooks to insert raw sql.

References on django-developers google group:

* https://groups.google.com/forum/?fromgroups#!topic/django-developers/xN0aMzrmA1Y
* https://groups.google.com/forum/?fromgroups#!topic/django-developers/KhsGj1b6rnU

Notes

  • All methods / hook-handlers should return a list of sql or raise NotImplementedError.
  • I did not want to base all work in django signals, so I tried the sql generation for these hooks is quite simple and can be used both as sqlall syncdb. Additionally, the signals were implemented, will not be recommended, but will be available. All that is done in the signals will not be available at the output of sqlall.
  • It is proposed to use the existing signal "post_syncdb" to model, app, and project. In my opinion is the signal used for more things you should. I will respect the decision, but I think it should have different signals for each case.

Current implementation

Signals

Add new parameter "type" to post_syncdb signal and add pre_syncdb signal without created_models parameter. type parameter identifies the context. Contexts: migrate, sync, flush.

Project level pre and post syncdb hooks

Signals: TODO

The addition of two new settings to explicitly specify two handlers: pre and post syncdb at the project level. If these handlers are run with "connection" as a parameter.

pre_sync runs before anything, and post_sync runs at the end of everything.

Settings:

  • settings.PROJECT_PRE_SYNCDB_HOOK
  • settings.PROJECT_POST_SYNCDB_HOOK

App level pre and post syncdb hooks

By default, you will find two functions: "post_sync" and "pre_sync" in the models of the app. If they exist, are executed with "connection" as a parameter. The sql obtained from "pre_sync" runs just before starting to create tables, and sql obtained from "post_sync" runs after creating all the tables.

Signals

post_syncdb signal is sended on all models are created. pre_syncdb signal is sended for all apps before tables creation.

Model level pre and post syncdb hooks

This is managed by two methods at model level, "get_post_sync_sql" and "get_pre_sync_sql". They should be decorated as "classmethod".

"get_post_sync_sql" are executed after all tables are created and are custom sql fixtures are loaded.

"get_pre_sync_sql" at the moment are not implemented. Not very clear to me when to run:

  • For each model just before creating the tables?
  • Before creating any table, run all sql pre_sync?

TODO

  • project level signal on pre and post syncdb.
  • post_flush hook for model.
  • pre_sync hook for model.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment