I have a legacy MySQL db, and I am trying to create Django models from it so I can use the legacy tables in my Django application. I ran inspectdb on the MySQL db and it seemed to import most fields correctly, but failed to import every single primary key and/or id field. Is this the expected behavior? I will admit I’m new to Django but I find it odd that Django wouldn’t use a primary key/id in the same way as SQL. The legacy db holds 17 tables, but I’m only showing one since the behavior was the same for all. Thanks for any insight you might have!
Legacy MySQL table “client”
CREATE TABLE `client` ( `id` INT(10) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci', `address` VARCHAR(128) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci', `manager_id` INT(10) NULL DEFAULT NULL COMMENT 'User_id of primary contact of client', `company_id` INT(10) NULL DEFAULT NULL, `facility_id` INT(10) NULL DEFAULT NULL COMMENT 'Likely needs to change to list of facilities (if one client uses multiple facilities within a company)', PRIMARY KEY (`id`) USING BTREE, INDEX `FK_facility_client` (`facility_id`) USING BTREE, INDEX `FK_user_client` (`manager_id`) USING BTREE, CONSTRAINT `FK_facility_client` FOREIGN KEY (`facility_id`) REFERENCES `ctsclouddev`.`facility` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT `FK_user_client` FOREIGN KEY (`manager_id`) REFERENCES `ctsclouddev`.`user_directory` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION)
Result of python manage.py inspectdb > models.py
class Client(models.Model): name = models.CharField(max_length=50, blank=True, null=True) address = models.CharField(max_length=128, blank=True, null=True) manager = models.ForeignKey('UserDirectory', models.DO_NOTHING, blank=True, null=True) company_id = models.IntegerField(blank=True, null=True) facility = models.ForeignKey('Facility', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'client'
Thanks in advance for any tips you might have. I searched around for an hour or so but couldn’t find anything on this specific issue.
Advertisement
Answer
Django models by default assign an automatic primary key called id
to each model. So, your definitions do include the id
fields, just hidden from view.