inspectDB and 'id' can only be used as a field name if the field also sets 'primary_key=True'.

3,109 views
Skip to first unread message

Carl Brewer

unread,
Mar 23, 2017, 7:21:51 AM3/23/17
to Django users
G'day,
Very new to Django, I'm trying to connect to an existing MySQL database that I am not familiar with.  I used inspectDB to load up the database models.py file, and am seeing these errors for some of the tables :

'id' can only be used as a field name if the field also sets 'primary_key=True'.

inspectDB gave me this :

class Access(models.Model):
    udid = models.CharField(max_length=40)
    id = models.IntegerField(db_column='ID')  # Field name made lowercase.
    access_date = models.DateField()
    access_type = models.CharField(max_length=40)
    version = models.CharField(max_length=20, blank=True, null=True)
    loginid = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'Access'


And the table looks like this :

CREATE TABLE `Access` (
  `udid` varchar(40) NOT NULL,
  `ID` int(11) NOT NULL,
  `access_date` date NOT NULL,
  `access_type` varchar(40) NOT NULL,
  `version` varchar(20) DEFAULT NULL,
  `loginid` text,
  KEY `udid_idx` (`udid`) USING HASH,
  KEY `udid_idx2` (`ID`,`udid`) USING HASH,
  KEY `udid_idx3` (`access_date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Is this something I need to set manually in models.py?  I'm not certain if ID is a suitable primary key or not - if the primary key is udid, or if it's a mashup of ID and udid, can I tell models.py about it and if so, how?
Pointers to relevant documentation much appreciated!

Thank you!

Carl


Camilo Torres

unread,
Mar 23, 2017, 7:05:08 PM3/23/17
to Django users
Hi.

You should rename the "id" field in your model to something else. You can edit your models.py and put another name, like "dbid" or something.

Django models reserve the "id" field for primary key; your table has another field as primary key.

Reply all
Reply to author
Forward
0 new messages