8

I have an existing MySQL database with several tables already populated with data. I created and configured a Django project with an application. Communication between Django and the database works as expected. I have generated a 'models.py' using 'inspectdb' command to create all my application models:

python manage.py inspectdb > myapp/models.py

My issue is that none of my models shows any 'id' field in 'models.py'. All existing MySQL tables having an 'id' column as primary key (auto increment being enabled for those) it seems weird.

I wonder if I need to explicitly add 'id' primary keys fields in all model classes created with inspectdb or if it is not needed (it would be implicit in that case).

Why 'id' primary key is missing from Django models definitions and should I add this field to the models classes?

Current setup

  • Python version: 3.6.8
  • Django version: 2.2.5
  • mysqlclient: 1.4.4
  • sqlparse: 0.3.0
donmelchior
  • 893
  • 3
  • 13
  • 31

2 Answers2

9

Why 'id' primary key is missing from Django models definitions and should I add this field to the models classes?

No. If you do not specify a primary key in your models. Django will automatically add a AutoField to your model named id, as is specified in the documentation on Automatic primary key fields:

By default, Django gives each model the following field:

id = models.AutoField(primary_key=True)

This is an auto-incrementing primary key.

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key, it won't add the automatic id column.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 2
    What I found confusing, was the comment added by `inspectdb`: "Make sure each model has one field with primary_key=True" which for a django novice seemed to indicate something else. This answer clears this up well. – Kristian Aug 24 '20 at 12:34
1

I am here with the same situation. The difference is that I am migrating from mssql database. As mentioned by @williem , Django automatically assigns an 'id'. You are more likely to get Programming error while using ForeignKey relationships as there are chances of conflict for the primary key. You may find this useful in that case : [Django Programming error column does not exist even after running migrations

Srijwal R
  • 552
  • 9
  • 16