django
January 27, 2024

Django: inspectdb command auto generating ID fields? Here is why

To begin with, I prefer to share official documentation of inspectdb :

https://docs.djangoproject.com/en/5.0/howto/legacy-databases/

Well, usually we work with databases using DBMS tools, like Navicat. Which means, there is rare writing models one-by-one in Django ORM. In such cases, we use inspectdb command of Django to make our life easier. I hope you got the point about this command at least by reading the documentation above. Now, I'll turn into a problem and start creating a new table, say user:

`user` table creation

Let's assume that you have already connected your database to Django project:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '<your_db_name>',
        'USER': '<your_db_user>',
        'PASSWORD': '<your_db_password>',
        'HOST': '<your_db_host>',
        'PORT': '5432'
    }
}

and there is at least one app on that project. I created a test app psql_app and now run python manage.py inspectdb > psql_app/models.py. Nothing happens on Command prompt, but when you open your models.py you can see generated tables:

Generated `user` table

Well, that's normal. But stop! ID field is popped up somehow! When we work with ORM after generating the table, undoubtedly encounter problems related to this ID field, and that is the issue you are facing with too.

Before turning into a solution, let's create another table courses :

`course` table generation

We should point out that in this case we set the ID field type to serial . To learn more about serial:

https://www.tutorialsteacher.com/postgresql/serial-type

When we save the table, the type becomes int4 automatically, but:

`course` table, sequence generation

As we can see, postgresql auto generates a sequence for us. Now, again we run inspectdb and see the result:

Generated `course` table

ID field is not present! So we solved the problem. It is very essential to pay attention on types of fields while creating a database tables using both DBMS tools and ORMs. Thanks for your attention.