I have created model in django for my database. After trying to add data to table I got this error:
`
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...
^
I am not really sure where is the problem since I have checked everything and did not find any declaration of source_id_id column.
Here is my model:
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"'
And I used manual migration so here is my SQL file:
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
);
And this is the function I am using to add data to database:
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
>Solution :
If you make a ForeignKey named foo, django uses foo_id as name of the column to store the primary key it refers to.
So you can rename the ForeignKey to 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"'