Working with composite primary key in django project with legacy database

后端 未结 2 1235
执念已碎
执念已碎 2021-01-12 22:00

I have a legacy database, where some table contains composite primary key. The model I get by running manage.py inspectdb command looks like this.



        
相关标签:
2条回答
  • 2021-01-12 22:15

    You must Delete managed = False command from the model to be able to edit your table

    0 讨论(0)
  • 2021-01-12 22:24

    Unfortunately django does not yet have a composite primary key (composite primary keys are also called multi column primary keys)

    There is a third party library, unsurprisingly name django-compositekey that makes it possible to create a model that has a multi column primary key. However that project is not maintained and not compatible with the latest versions of django.

    Your best bet, is to add a new column into your table which is a an AutoField and make it the new primary key. The fields that make up the primary key at present can then be marked as unique_together. While this may not be ideally for a few queries. It's good enough for most.

    If you update your question with the current table structure (as shown in your sql console) I will update my answer to show what the model will look like.

    Update There are lots of different ways in which you can drop the old composite primary key and replace it with a new auto increment primary key. Here is the easiest, it involves just SQL

    CREATE TABLE newtable LIKE mytable;
    ALTER TABLE newtable DROP PRIMARY KEY;
    ALTER TABLE newtable ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
    RENAME TABLE mytable to mytable_old;
    RENAME TABLE newtable to mytable;
    INSERT INTO mytable(userid,field1id, rest of the fields) 
        SELECT * FROM mytable_old;
    

    Then edit your model and remove the primary_key=True flag from those fields.

    Footnote:
    Some databases like sqlite for example does not support the LIKE clause in a CREATE TABLE. In these cases, you will have to look up the create table statement for the original table, and copy paste after editing the table name. Judging by your table structure you seem to be using mysql and it supports the LIKE clause.

    0 讨论(0)
提交回复
热议问题