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 josephbiko)

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 josephbiko, 6 years ago

Owner: changed from nobody to josephbiko
Status: newassigned

comment:2 by josephbiko, 6 years ago

Owner: josephbiko removed
Status: assignednew

comment:3 by Simon Charette, 6 years ago

Component: UncategorizedMigrations
Resolution: needsinfo
Status: newclosed
Type: UncategorizedBug

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.fkshould be automatically repointed to B.a_ptr when A 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.

comment:4 by Simon Charette, 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 josephbiko, 6 years ago

Cc: josephbiko added
Description: modified (diff)
Resolution: needsinfo
Status: closednew
Note: See TracTickets for help on using tickets.
Back to Top