我正在从 MySQL 后端切换到 PostgreSQL 后端,并且遇到了一些模型继承问题。以下是模型示例:
class Parent(models.Model):
key = models.Charfield(...)
value = models.Charfield(...)
content_type = models.ForeignKey(ContentType)
object_id = models.CharField(max_length=200)
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Child1(Parent):
pass
class Child2(Parent):
pass
我们有两个这样的子类的原因是,我们在另一个模型中模拟两个键/值对,并希望将它们分成两个表以便于查找。通用 FK 也用于将其附加到其他模型。这种继承设置在 MySQL 中运行良好,但是当我将其切换到 PostgreSQL 时,在尝试运行我们的测试时出现错误(但 syncdb 运行良好)。就好像 Django 可以接受这种关系,但 PostgreSQL 不喜欢正在生成的 SQL。当我查看从 syncdb 生成的内容时,我看到了这一点:
CREATE TABLE "myapp_parent" (
"id" serial NOT NULL PRIMARY KEY,
"key" varchar(200) NOT NULL,
"value" varchar(200) NOT NULL,
"content_type_id" integer NOT NULL REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED,
"object_id" varchar(200) NOT NULL);
CREATE TABLE "myapp_child1" (
"parent_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "myapp_parent" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE "myapp_child2" (
"parent_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "myapp_parent" ("id") DEFERRABLE INITIALLY DEFERRED);
所以一切看起来都是正确的,然后当我运行我的测试时,我得到了这个:
Error: Database test_myapp couldn't be flushed. Possible reasons:
* The database isn't running or isn't configured correctly.
* At least one of the expected database tables doesn't exist.
* The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: column "id" of relation "myapp_child1" does not exist
当我运行冲洗时:
SELECT setval(pg_get_serial_sequence('"myapp_child1"','id'), 1, false);
我尝试在子模型中手动添加一个 ID 字段作为主键,但 Django 抛出一个错误,说它与父的 ID 字段冲突。我该如何解决这个问题,以便 PostgreSQL 喜欢它?并提前感谢。