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
If you don't specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don't need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.
By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.
Thus, an id AutoField that auto increments on every instance of that model is created by default when you run makemigrations on the project.
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
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 setField.primary_key
, it won't add the automaticid
column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With