Tracking Django Schema Changes with django-schema-history
A package that records every AddField, RemoveField and AlterField so schema history is reviewable in the admin.
Read the original on Medium ↗§1Introduction
Managing database schema changes is a crucial aspect of Django development. Keeping track of modifications such as adding, removing, or altering fields can be challenging, especially in collaborative projects. To simplify this process, we introduce Django-Schema-History, a package that automatically records schema changes for your Django models.
§2Why Use Django-Schema-History?
- Automatic tracking: Monitors and logs changes in your database schema.
- Easy integration: Works seamlessly with Django’s migration system.
- Historical insights: Provides a structured record of schema modifications for debugging and auditing.
- Admin integration: Allows reviewing schema changes directly in the Django admin panel.
§3Installation
To install the package, run:
pip install django-schema-historyThen, add it to your INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
...
'schema_history',
]Run migrations to create the necessary tables:
python manage.py migrate schema_history§4How It Works
Django-Schema-History captures schema changes by analyzing migration operations. It detects modifications such as:
- AddField: When a new field is added.
- RemoveField: When an existing field is removed.
- AlterField: When a field is modified.
These changes are stored in the SchemaChange model, which records:
- The model name
- The field name
- The type of change (added, removed, or modified)
- The timestamp of the change
§5Usage
After installing the package, schema changes will be tracked automatically. You can access them via Django’s shell:
python manage.py track_migrationOr review changes in the Django admin panel by registering the model:
from django.contrib import admin
from schema_history.models import SchemaChangeadmin.site.register(SchemaChange)§6Example Output
Suppose you add a new field email to the User model and run migrations. The following entry will be recorded:
Model Field Change Type User email added_field
Similarly, if you remove a field or modify an existing one, the changes will be logged accordingly.
§7Contributing
Contributions are welcome! If you find issues or want to suggest improvements:
- Fork the repository
- Create a new branch (feature-name)
- Submit a pull request
§8Conclusion
Django-Schema-History makes tracking database changes effortless. Whether you’re working solo or in a team, having a historical record of schema modifications can be invaluable. Install it today and simplify your Django development workflow!
For more details, see the repository: github.com/mn2rb/django-schema-history