如何在Django Model中定义多主键和外键

时间:2015-12-03 00:13:33

标签: python django django-models

我在Mysql DB中有两个表,它看起来像这样:

Table1:
   number  int  pk
   type    int  pk
   ...

Table2:
   number  int  pk fk
   type    int  pk fk
   ...

我在models.py中定义了像这样的模型

def Table1:
   class Meta:
      unique-together = ('number', 'type'),
      index-together = ('number', 'type'),

   primary = ('number', 'type')   

   number = models.IntegerField()
   type = models.IntegerField()
   ...

当我迁移模型时,结果并非我想要的结果。

    BEGIN;
--
-- Create model Table1
--
CREATE TABLE "multiprimary_table1" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "number" integer NOT NULL, "type" integer NOT NULL);
--
-- Alter unique_together for table1 (1 constraint(s))
--
ALTER TABLE "multiprimary_table1" RENAME TO "multiprimary_table1__old";
CREATE TABLE "multiprimary_table1" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "number" integer NOT NULL, "type" integer NOT NULL);
INSERT INTO "multiprimary_table1" ("type", "id", "number") SELECT "type", "id", "number" FROM "multiprimary_table1__old";
DROP TABLE "multiprimary_table1__old";
CREATE UNIQUE INDEX "multiprimary_table1_number_8d499fc9_uniq" ON "multiprimary_table1" ("number", "type");
--
-- Alter index_together for table1 (1 constraint(s))
--
ALTER TABLE "multiprimary_table1" RENAME TO "multiprimary_table1__old";
CREATE TABLE "multiprimary_table1" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "number" integer NOT NULL, "type" integer NOT NULL);
INSERT INTO "multiprimary_table1" ("type", "id", "number") SELECT "type", "id", "number" FROM "multiprimary_table1__old";
DROP TABLE "multiprimary_table1__old";
CREATE UNIQUE INDEX "multiprimary_table1_number_8d499fc9_uniq" ON "multiprimary_table1" ("number", "type");
CREATE INDEX "multiprimary_table1_number_8d499fc9_idx" ON "multiprimary_table1" ("number", "type");

COMMIT;

Django在我的表中添加ID并将主键设置为ID列,我该如何解决? 而且我也不知道如何定义多个外键,有人可以告诉我吗?

1 个答案:

答案 0 :(得分:0)

Django Composite Key可能是您的解决方案:

https://github.com/simone/django-compositekey