Django detect and rollback unintentional database tables change

Django detect and rollback unintentional database tables change

For sharing purpose, I accidentally modified my database tables. This is my ‘semi-automatic’ way to detect and rollback the changes.

Please share if you have better detection and rollback methods :grin:

Context

  1. I give django full control over my database (not recommended)
  2. I do it in ‘strict’ mode, database tables should be exactly as defined in models.py
    • no manual change allow
    • no other web framework / software change allow

Detect

  1. ./manage.py inspectdb → this will introspects the database tables in the given database and outputs a Django model module
  2. manually compare the output with the models.py

I am not satisfy with this manual inspection, probably can write some logic to automatically compare the output with models.py

Rollback

  1. export the affected table(s) data 1st
  2. ./manage.py migrate thatchangedapp 0xxx → rollback
  3. ./manage.py migrate → apply migration
  4. import the data programmatically, with the necessary data transformation

Does the --check option to makemigrations help here?

--check
Makes makemigrations exit with a non-zero status when model changes
without migrations are detected.

1 Like

Nice~ :slight_smile:

Using this method, we need to 1st make changes to the model, then do the check.

But you gave me an idea, instead of writing custom automated check, maybe we can “hack” it to call the --check function directly, need to check the django source code.