Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do id primary key have to be explicitly defined in Django models generated from inspectdb against an existing database?

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
like image 702
donmelchior Avatar asked Oct 03 '19 11:10

donmelchior


People also ask

Does Django automatically create primary key?

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.

How can create primary key in Django model?

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.

Does Django auto generate ID?

Thus, an id AutoField that auto increments on every instance of that model is created by default when you run makemigrations on the project.

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.


1 Answers

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.

like image 113
Willem Van Onsem Avatar answered Sep 22 '22 13:09

Willem Van Onsem