Opened 6 years ago
Last modified 6 weeks ago
#29574 new Bug
Django Foreign Key Mismatch — at Version 5
Reported by: | josephbiko | Owned by: | |
---|---|---|---|
Component: | Migrations | Version: | 2.1 |
Severity: | Normal | Keywords: | |
Cc: | josephbiko | Triage Stage: | Accepted |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
Django Foreign key's do not track the models DB when the model is inherited from abstract class.
Steps to reproduce:
create models:"
class A(models.Model): field = models.IntegerField() class Meta: abstract = True class B(A): field2 = models.IntegerField() class C(models.Model): fk = models.ForeignKey(B,on_delete=models.CASCADE)
migrate
change the models (by removeing the meta )to:
class A(models.Model): field = models.IntegerField() class B(A): field2 = models.IntegerField() class C(models.Model): fk = models.ForeignKey(B,on_delete=models.CASCADE)
run migrations.
Now add an object of class B in the admin.
resulting error:
"foreign key mismatch - "models_c" referencing "models_b""
Change History (5)
comment:1 by , 6 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:2 by , 6 years ago
Owner: | removed |
---|---|
Status: | assigned → new |
comment:3 by , 6 years ago
Component: | Uncategorized → Migrations |
---|---|
Resolution: | → needsinfo |
Status: | new → closed |
Type: | Uncategorized → Bug |
comment:4 by , 6 years ago
Upon further inspection I assume you had an existing B
entry before attempting to run the migration that adds the B.a_ptr
primary key and it failed because no rows were present in the newly added A
table?
In this case I think you should be in charge of populating A
with a data migration (either using RunPython
or RunSQL
) instead of expecting Django to do it for you.
comment:5 by , 6 years ago
Cc: | added |
---|---|
Description: | modified (diff) |
Resolution: | needsinfo |
Status: | closed → new |
Hello josephbiko,
I assume you meant that running
makemigrations
between your two model scenarios doesn't generate the appropriate database alterations?There's a few bugs (#23521, #25247) related to switching from concrete to abstract inheritance but in the abstract to concrete case there shouldn't be any problem as
C.fk
should be automatically repointed toB.a_ptr
whenA
is made concrete.I'm afraid we'll need a more detailed reproduction test case in order to reproduce your issue. Please include tracebacks and detail every steps your perform to get there.