Using Django with an existing database field problem

I am using Django with an existing database. I used inspectdb to create models of an existing database. Everything works, except for one important detail. Django seems to always assume that an id field exists . For example, when I remove a field named date , run the migration, the date is removed from the table. However, when I try to remove the id field , it says -Alter field id to table_name , even if there is no id field in the actual database table.

So if you want to create 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?

+3


source to share


1 answer


By default, Django creates a field id

for your models even if you don't specify it, so in this case even if you remove the autogenerated one:

id = models.IntegerField(primary_key=True)

      

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

So yes, you must specify your primary key by adding an attribute primary_key=True

to the corresponding field of the generated model inspectdb

, or Django will read your primary key as a column id

.



Keep in mind that if you decide to add a column id

to your table, you do not have to specify it explicitly in your model :

Each generated model has an attribute for each field, including the primary key id fields. However, remember that Django will automatically add the id primary key field if the model doesn't have a primary key. Thus, you want to remove any lines that look like this:

id = models.IntegerField(primary_key=True)

These rows are not only redundant, but can also cause problems if your application adds new records to these tables.

If you choose not to do this, make sure there are no NULL

or duplicate values in the column that you will eventually select as PK .

+2


source







All Articles