Why are foreign keys rewritten when adding related_name?

32 views
Skip to first unread message

Hanne Moa

unread,
Mar 1, 2019, 2:40:01 AM3/1/19
to django...@googlegroups.com
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

Simon Charette

unread,
Mar 1, 2019, 3:16:23 PM3/1/19
to Django users
Hello HM,

I know that some changes have been made to avoid unnecessary foreign key
rebuilds on some option changes.

Are you experiencing this on 2.1 and 2.2 pre release?

Simon

Hanne Moa

unread,
Mar 4, 2019, 3:03:17 AM3/4/19
to django...@googlegroups.com
No, 1.11. This project is still on Python 2.7 but I do think we'll
have it on Python 3(.5) before the year is over.
> --
> 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...@googlegroups.com.
> To post to this group, send email to django...@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/a1d9f7a9-be2a-41d5-8a43-4b468ad4a547%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages