Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django with an existing database id field trouble

I'm using Django with an existing database. I used inspectdb to create the models of the existing database. Everything works except for one important detail. It seems as though Django always assumes that there is an id field. For example, when I delete a field called date the run a migration, date is deleted from the table. However, when I try to delete the id field, it says -Alter field id on table_name even if there is no id field in the actual database table.

So, if you want make and use an id field in an existing database do you have to manually specify it in the model and database or is there a better way?

like image 286
Hudson Worden Avatar asked Oct 23 '25 08:10

Hudson Worden


1 Answers

By default Django creates an id field for your models even if you don't specify it, so, in this case, even if you delete the autogenerated:

id = models.IntegerField(primary_key=True)

Django models will assume one exists, thus the message you see. This is because you need to have one primary key field.

So, yes, you have to specify your primary key by adding the primary_key=True attribute to the appropriate field on the model generated by inspectdb, or Django will assume your primary key is column id.

Keep in mind that, if you decide to add an id column to your table, you shouldn't set it explicitly in your model:

Each generated model has an attribute for every field, including id primary key fields. However, recall that Django automatically adds an id primary key field if a model doesn’t have a primary key. Thus, you’ll want to remove any lines that look like this:

id = models.IntegerField(primary_key=True)

Not only are these lines redundant, but also they can cause problems if your application will be adding new records to these tables.

If you decide not to, make sure the column you end up choosing as PK doesn't have NULL nor repeated values.

like image 90
kirbuchi Avatar answered Oct 25 '25 21:10

kirbuchi