Django - Inspectdb support this kind of database tables?
我已经对"inspectdb"进行了测试,但我认为我的架构过于复杂,因为
例如...对于表"tdir_files_context"(djangoinspectdb.JPG
"附件中的图像")我得到了这个模型:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class TdirFilesContext(models.Model): id_category = models.ForeignKey(TdirCategories, db_column='id_category') id_file_context = models.CharField(max_length=20) n_file_context = models.CharField(max_length=150) coment = models.CharField(max_length=2000) id_user_db_ins = models.CharField(max_length=45) id_user_db_upd = models.CharField(max_length=45) id_user_sys_ins = models.CharField(max_length=45) id_user_sys_upd = models.CharField(max_length=45) date_ins = models.DateTimeField() date_last_upd = models.DateTimeField() class Meta: db_table = u'tdir_files_context' |
这个数据库表有两个主键和一个外键。这
Django Model 处理这种数据库表?
首先,没有表可以有两个主键。那是不可能的。我只是假设你的主键由两列组成,
不幸的是,Django 目前不支持具有复合主键的模型,它只能处理只有一列作为主键的表。
除此之外,
koniiiik 刚刚带来了一个关于复合主键的非常有趣的答案。
但是当我看到您对模型的定义时,我不确定您是否真的想要两个主键,而只是一个外键和一个主键:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class TdirCategories(models.Model): id_category = models.AutoField(primary_key=True) class TdirFilesContext(models.Model): id_category = models.ForeignKey(TdirCategories, db_column='id_category') id_file_context = models.AutoField(primary_key=True) n_file_context = models.CharField(max_length=150) coment = models.CharField(max_length=2000) id_user_db_ins = models.CharField(max_length=45) id_user_db_upd = models.CharField(max_length=45) id_user_sys_ins = models.CharField(max_length=45) id_user_sys_upd = models.CharField(max_length=45) date_ins = models.DateTimeField() date_last_upd = models.DateTimeField() class Meta: db_table = u'tdir_files_context' |
命令
之后
你答对了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | BEGIN; CREATE TABLE"app_tdircategories" ( "id_category" integer NOT NULL PRIMARY KEY ) ; CREATE TABLE"tdir_files_context" ( "id_category" integer NOT NULL REFERENCES"app_tdircategories" ("id_category"), "id_file_context" integer NOT NULL PRIMARY KEY, "n_file_context" varchar(150) NOT NULL, "coment" varchar(2000) NOT NULL, "id_user_db_ins" varchar(45) NOT NULL, "id_user_db_upd" varchar(45) NOT NULL, "id_user_sys_ins" varchar(45) NOT NULL, "id_user_sys_upd" varchar(45) NOT NULL, "date_ins" datetime NOT NULL, "date_last_upd" datetime NOT NULL ) ; COMMIT; |
希望对你有帮助:)