Django automatically create primary keys for existing database tables
Asked Answered
G

1

7

I have an existing database that I'm trying to access with Django. I used python manage.py inspectdb to create the models for the database. Currently I'm able to import the models into the python shell however when I try to access any of the actual objects in any way, I get this error OperationalError: (1054, "Unknown column 'some_table.id' in 'field list'"). I see that the table in the database in fact does not have an id field. How can I fix this? Do I need to update the managed field in the Meta class and run a migration so it can create this field automatically?

Gobelin answered 1/6, 2015 at 23:39 Comment(0)
E
7

From the Django documentation: This feature is meant as a shortcut, not as definitive model generation. See the documentation of inspectdb for more information. (Reference: https://docs.djangoproject.com/en/1.8/howto/legacy-databases/)

You're going to need to manually clean up the models and migrate. The line you'll have to add for adding the "id" field is:

id = models.IntegerField(primary_key=True)

Warning: I'd definitely create a copy of the database to toy with, rather than the original. This will likely take you some trial and error to get right. After you're absolutely sure you have it right, you can changed Managed=True, but be VERY careful!

Embankment answered 2/6, 2015 at 0:2 Comment(2)
Sweet! Thanks. So I guess if I determine if an existing field within a table should be the primary key I would just set the primary_key attribute to true?Gobelin
Let us know if you need more help, this can get tricky (I've only done it twice myself), so definitely be careful with your source data! Mark the answer as correct when you get a chance?Embankment

© 2022 - 2024 — McMap. All rights reserved.