Creating Django models of an existing DB

Django makemiggrations and migrate command create tables from models as per details in models.py file but what if you have already created database ? creating model manually looking at DDL is cumbersome but you need not worry, Django provides an utility called as inspectdb to get this done.

How to use inspectdb ?

Step#1

inspectdb Introspects the database tables in the database pointed-to by the NAME setting.py and outputs a Django model. To use this utility cd to project home folder on terminal.

Step#2

To view models on terminal

python3 manage.py inspectdb

to generate file using inspectdb

python3 manage.py inspectdb > tempmodels.py

Please note above file will take database name from Django settings file and generate model.

If you want to generate model only for specific table

python3 manage.py inspectdb todo_task > tempmodels.py

Many times database have admin related tables whose models are not needed in your application so its a good idea to remove them from models.py or generate by providing table name as parameter.

Here is sample file generated using inspectdb

# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models


class TodoTask(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField()
    created_date = models.DateField(blank=True, null=True)
    due_date = models.DateField(blank=True, null=True)
    completed = models.BooleanField()
    completed_date = models.DateField(blank=True, null=True)
    note = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'todo_task'

After this model is generated you need cross check it for data type, primary key and foreign key.

This takes care of make migrations part, you still have to run migrate command to create django admin related tables in database. Run following command once models.py file is ready

python3 manage.py migrate

Troubleshooting


$ python3 manage.py inspectdb
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.

login to postgres command prompt and execute following command


ecommpedia1=#  GRANT ALL PRIVILEGES ON TABLE ecomm_time TO ecommuser;
GRANT

This happens when you have created table after granting privileges on database to specific user. Since this table did not exists earlier, you need to GRANT privileges.

Most Importantly , making migration manually will not work with this autogenerated modell because it has following statement

managed = False

If you make any change to the model and needs to apply this to database, comment this line and then run makemigrations command

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.