Site icon Tutorial

Integrating with a Legacy Database

Django’s database layer generates SQL schemas from Python code — but with a legacy database, you already have the SQL schemas. In such a case, you’ll need to create models for your existing database tables. For this purpose, Django comes with a tool that can generate model code by reading your database table layouts. This tool is called inspectdb, and you can call it by executing the command manage.py inspectdb.

Using inspectdb – The inspectdb utility introspects the database pointed to by your settings file, determines a Django model representation for each of your tables, and prints the Python model code to standard output. Here’s a walk-through of a typical legacy database integration process from scratch. The only assumptions are that Django is installed and that you have a legacy database.

 

python mysite/manage.py inspectdb > mysite/myapp/models.py

Cleaning Up Generated Models – As you might expect, the database introspection isn’t perfect, and you’ll need to do some light cleanup of the resulting model code. Here are a few pointers for dealing with the generated models:

 

id = models.IntegerField(primary_key=True)

Not only are these lines redundant, but also they can cause problems if your application will be adding new records to these tables. The inspectdb command cannot detect whether a field is autoincremented, so it’s up to you to change this to AutoField, if necessary.

If a field in your database has no good Django equivalent, you can safely leave it off. The Django model layer is not required to include every field in your table(s).

 

For example, if a table has an INT column called for, the generated model will have a field like this:

for_field = models.IntegerField(db_column=’for’)

inspectdb will insert the Python comment ‘Field renamed because it was a Python reserved word.’ next to the field.

Back to Tutorial

Exit mobile version