issue with self foreign key
quertenmont opened this issue · 2 comments
Hello,
I am trying to generate a partitioned table for a model of that kind:
class PostMaster(PostgresPartitionedModel):
class PartitioningMeta:
method = PostgresPartitioningMethod.RANGE
key = ["created"]
id = models.CharField(max_length=128, null=False, primary_key=True)
created = models.DateTimeField(null=True, db_index=True)
parent_post = models.ForeignKey("self", on_delete=models.PROTECT, null=True, related_name="replies")
The issue seems to come from the fact that the actual primary of the model would become (created, id) because of the pagination,
but the parent_post foreign key would only contains the "id".
The error I am getting during the creation migration is the following one:
ERROR: there is no unique constraint matching given keys for referenced table "myapp_postmaster"
and it is caused by the line:
ALTER TABLE "myapp_postmaster" ADD CONSTRAINT "myapp_postmaster_parent_post_id_720ab849_fk_myapp_postmaster_id" FOREIGN KEY ("parent_post_id") REFERENCES "myapp_postmaster" ("id") DEFERRABLE INITIALLY DEFERRED;
do you know any workaround for this issue ?
Thanks in advance
Loic
in case someone have the same difficulty, the workaround I found was to add the to_field in the foreign key,
one also need to disable the db constraint at the same place:
parent_post = models.ForeignKey("self", on_delete=models.PROTECT, null=True, related_name="replies", to_field="id", db_constraint=False)
The joins get a bit slower, in particular, but at least it works.