Django - Compare Model Code to Database
I maintain a Django project with a database that has several model constraints that have fallen out of sync with the actual database. So, for example, some model fields have null=False set, but the database permits NULLs for the corresponding database column.
I'm curious if there is a utility, eithe开发者_StackOverflow中文版r in Django or a third-party Python script, that will compare the SHOW CREATE TABLE output (in this case, using MySQL syntax) for each table and compare it with the python manage.py sql output, to highlight the discrepancies.
Granted, in an ideal situation, the database wouldn't fall out of sync with the Django model code in the first place, but since that's where I am, I'm curious if there's a solution to this problem before I write one myself or do the comparison manually.
./manage.py inspectdb
generates the model file corresponding to the models that exist within the database.
You can diff it with your current model files using a standard unix diff or any other fancy diffing tool to find the difference and plan your migration strategy.
While the former seems simpler and better, you can also see the diff at the sql level. ./manage.py sqlall
generates the sql for the current db schema and correspondingly show create table table-name
shows the sql for the table creation.
You might want to refer http://code.google.com/p/django-evolution/ which once auto migrated the state of the db to the one in the current models. - Note however, that this project is old and seems abandoned.
I did come up with a quick and dirty means of doing what I described. It's not perfect, but if you run ./manage.py testserver
, the test database will be created based on the model code. Then (using MySQL-specific syntax), you can dump the schema for the regular database and the test database to files:
$ mysqldump -uroot -p [database_name] --no-data=true > schema.txt
$ mysqldump -uroot -p [test_database_name] --no-data=true > test_schema.txt
Then you can simply diff schema.txt and test_schema.txt and find the differences.
For PostgreSQL, do a manage.py syncdb
on a temporary empty database, then dump production and temporary databases with pg_dump -sOx
and compare the resulting files. Among visual diff tools, at least GNOME Meld seems to cope well with PostgreSQL dumps.
精彩评论