While Django is best suited for developing new applications, it’s quite possible to integrate it into legacy databases. Django includes a couple of utilities to automate as much of this process as possible.
This document assumes you know the Django basics, as covered in the tutorial.
Once you’ve got Django set up, you’ll follow this general process to integrate with an existing database.
You’ll need to tell Django what your database connection parameters are, and what the name of the database is. Do that by editing the DATABASES setting and assigning values to the following keys for the 'default' connection:
Django comes with a utility called inspectdb that can create models by introspecting an existing database. You can view the output by running this command:
$ python manage.py inspectdb
Save this as a file by using standard Unix output redirection:
$ python manage.py inspectdb > models.py
This feature is meant as a shortcut, not as definitive model generation. See the documentation of inspectdb for more information.
Once you’ve cleaned up your models, name the file models.py and put it in the Python package that holds your app. Then add the app to your INSTALLED_APPS setting.
If your plan is that your Django application(s) modify data (i.e. edit, remove records and create new ones) in the existing database tables corresponding to any of the introspected models then one of the manual review and edit steps you need to perform on the resulting models.py file is to change the Python declaration of each one of these models to specify it is a managed one. For example, consider this generated model definition:
class Person(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=70) class Meta: managed = False db_table = 'CENSUS_PERSONS'
If you wanted to modify existing data on your CENSUS_PERSONS SQL table with Django you’d need to change the managed option highlighted above to True (or simply remove it to let it because True is its default value).
This serves as an explicit opt-in to give your nascent Django project write access to your precious data on a model by model basis.
Next, run the syncdb command to install any extra needed database records such as admin permissions and content types:
$ python manage.py syncdb
Those are the basic steps – from here you’ll want to tweak the models Django generated until they work the way you’d like. Try accessing your data via the Django database API, and try editing objects via Django’s admin site, and edit the models file accordingly.
Jul 10, 2015