psycopg2.errors.UndefinedColumn:关系“service_approval_domains”的列“source_id_id”不存在

问题描述 投票:0回答:1

我已经在 django 中为我的数据库创建了模型。尝试将数据添加到表后,我收到此错误:

`

lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedColumn: column "source_id_id" of relation "service_approval_domains" does not exist
LINE 1: ...domains" ("domain", "created_at", "retrieved_at", "source_id...
                                                             ^

我不太确定问题出在哪里,因为我已经检查了所有内容,但没有找到任何

source_id_id
列的声明。

这是我的模型:

class ServiceApprovalDomains(models.Model):
    id = models.BigAutoField(primary_key=True)
    domain = models.TextField(unique=True ,null=False)
    created_at = models.DateTimeField(auto_now_add=True)
    retrieved_at = models.DateTimeField(auto_now=True)
    source_id = models.ForeignKey(
        ServiceApprovalDomainSources, on_delete=models.CASCADE
    )

    class Meta:
        managed = False
        db_table = '"privacy"."service_approval_domains"'

我使用了手动迁移,所以这是我的 SQL 文件:

CREATE TABLE "privacy"."service_approval_domains"(
    "id" BIGSERIAL PRIMARY KEY,
    "domain" TEXT UNIQUE NOT NULL,
    "created_at" timestamp with time zone not null default current_timestamp,
    "retrieved_at" timestamp with time zone default current_timestamp,
    "source_id" bigserial not null references service_approval_domain_sources("id") on delete cascade
);

这是我用来将数据添加到数据库的函数:

def add_domains(data: list[AddServiceApprovalDomains]):
    for domain in data:
        source = ServiceApprovalDomainSources.objects.get_or_create(name=domain.source.name)
        try:
            ServiceApprovalDomains.objects.create(domain=domain.domain, source_id=source[0])
        except IntegrityError:
            pass
    return True 
python django django-models psycopg2
1个回答
0
投票

如果您将

ForeignKey
命名为
foo
,django 使用
foo_id
作为列的名称来存储它所引用的主键。

因此您可以将

ForeignKey
重命名为
source
:

class ServiceApprovalDomains(models.Model):
    id = models.BigAutoField(primary_key=True)
    domain = models.TextField(unique=True, null=False)
    created_at = models.DateTimeField(auto_now_add=True)
    retrieved_at = models.DateTimeField(auto_now=True)
    source = models.ForeignKey(
        ServiceApprovalDomainSources, on_delete=models.CASCADE
    )

    class Meta:
        managed = False
        db_table = '"privacy"."service_approval_domains"'
© www.soinside.com 2019 - 2024. All rights reserved.