简体   繁体   中英

Django foreign keys as composite primary key

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

DDL First :

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 key, as well as both are composite primary key.

After 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'),)

Then when I run 'makemigrations' command, It gives me 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 code below 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's my COriginal_Data_Type_ID field and CTask_Name field?

OK Thanks to knbk and django dev's answer Yeah it was django's bug and There's a bug-fix code here :

https://raw.githubusercontent.com/jbzdak/django/ticket_251274/django/core/management/commands/inspectdb.py

You can download this and overwrite inspectdb.py file in :

C:\\Python27\\Lib\\site-packages\\django\\core\\management\\commands

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM