GarlicDipping
GarlicDipping

Reputation: 45

Django inspectdb 'unique_together' refers to the non-existent field (2015)

I'm using Django with MySQL and having a problem after using 'inspectdb' command to create my models.py file.

DDL:

CREATE TABLE YDB_Collects (
  COriginal_Data_Type_ID VARCHAR(16) NOT NULL,
  CTask_Name VARCHAR(16) NOT NULL,
  PRIMARY KEY (COriginal_Data_Type_ID, CTask_Name),
  INDEX FK_COLLECTS_TASK (CTask_Name),
  CONSTRAINT FK_COLLECTS_ORIGINAL_DATA_TYPE FOREIGN KEY (COriginal_Data_Type_ID) REFERENCES YDB_Original_Data_Type (Original_Data_Type_ID),
  CONSTRAINT FK_COLLECTS_TASK FOREIGN KEY (CTask_Name) REFERENCES YDB_Task (Task_Name)
)

As you can see, COriginal_Data_Type_ID and CTask_Name are foreign keys, as well as the composite primary key.

For this DDL, Django's 'inspectdb' command gave this model:

class YdbCollects(models.Model):
    coriginal_data_type = models.ForeignKey('YdbOriginalDataType', db_column='COriginal_Data_Type_ID')  # Field name made lowercase.
    ctask_name = models.ForeignKey('YdbTask', db_column='CTask_Name')  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'ydb_collects'
        unique_together = (('COriginal_Data_Type_ID', 'CTask_Name'),)

But when I run 'makemigrations' command, it gives me the error message:

'unique_together' refers to the non-existent field 'COriginal_Data_Type_ID' and 'CTask_Name'

When I change:

unique_together = (('COriginal_Data_Type_ID', 'CTask_Name'),)

into:

unique_together = (('coriginal_data_type', 'ctask_name'),)

then yeah, it goes OK. But is this correct way to go? Seems like the code has different schema from my DDL. Original foreign key I defined was ID of data type, not data type itself.

Did I do something wrong here? And where are my COriginal_Data_Type_ID and CTask_Name fields?

Upvotes: 2

Views: 1266

Answers (1)

GarlicDipping
GarlicDipping

Reputation: 45

This has been fixed in Django 1.10 and later (and backported to Django 1.8.8 and 1.9).

It was a Django bug and the fix is here: django/django@2cb50f9

It involved this change in django/core/management/commands/inspectdb.py:

# tup = '(' + ', '.join("'%s'" % c for c in columns) + ')'                        # Change this
  tup = '(' + ', '.join("'%s'" % column_to_field_name[c] for c in columns) + ')'  # to this
  unique_together.append(tup)

Upvotes: 0

Related Questions