Thursday, February 28, 2019

Why are foreign keys rewritten when adding related_name?

I added "related_name" to an exiting ForeignKey and checked with
"django-admin sqlmigrate" what would be done.

It seems that the foreign key constraint is dropped, then the exact
same constraint is added back. Why?

Example: If we have the classes:

class Wall(models.Model):
..

class Door(models.Model):
..wall = models.ForeignKey(Wall)

and change Door.wall to models.ForeignKey(Wall, related_name='walls'), then:

Prior to this, there exist (postgres) the constraint:

"app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES
app_wall(id) DEFERRABLE INITIALLY DEFERRED.

"django_admin sqlmigrate" reports:

SET CONSTRAINTS "app_door_wall_id_45647_fk_app_wall" IMMEDIATE; ALTER
TABLE "app_door" DROP CONSTRAINT
"app_door_wall_id_45647_fk_app_wall";
ALTER TABLE "app_door" ADD CONSTRAINT
"app_door_wall_id_45647_fk_app_wall" FOREIGN KEY ("wall_id")
REFERENCES "app_wall" ("id") DEFERRABLE INITIALLY DEFERRED;

After running the migration, which is run as there's stuff in the log,
there exists seemingly the same constraint as before:

"app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES
app_wall(id) DEFERRABLE INITIALLY DEFERRED.

Why waste a connection this way?

--
HM

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACQ%3DrrdbgWpcSgm85fDDskWNRXvYQ5hGyyo9yn5T5fyRj7%2BPQg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment