I'v two models
class A(models.Model):
index = models.SmallIntegerField(primary_key=True)
audio = models.FileField(null=True, blank=True)
x = models.SmallIntegerField()
y = models.SmallIntegerField(null=True, blank=True)
and
class B(models.Model):
b = models.ForeignKey(B, on_delete=models.CASCADE)
index = models.SmallIntegerField()
audio = models.FileField(null=True, blank=True)
image = models.FileField(null=True, blank=True)
I made a data migration that initializes model A objects (every object also creates B objects with it and every created B also creates C objects with it.) Here is the migration:
from django.db import migrations
def create_as(apps, schema_editor):
A = apps.get_model('super_app', 'A')
B = apps.get_model('super_app', 'B')
C = apps.get_model('super_app', 'C') # C has FK referencing B
# Some logic here that creates instances of A (also creates B and C)
def delete_as(apps, schema_editor):
A = apps.get_model('super_app', 'A')
A.objects.all().delete()
class Migration(migrations.Migration):
dependencies = [
('super_app', '00xx_the_very_previous_migration'),
]
operations = [
migrations.RunPython(create_as, delete_as)
]
The migrations is applied forward successfully.. but when I try to revert back the migration (Which should call delete_as) I'm always having this error:
ValueError: Cannot query "B object (757)": Must be "B" instance.
I've been trying and digging but no clue why this happens!
Note: The type of models in migrations are historical models (__fake__.{MODEL}) I tried to use the latest state of the model by doing:
def delete_as(apps, schema_editor):
A = apps.get_model('super_app', 'A')
from django.apps import apps # FIXME. This gives latest models state.
B = apps.get_model('super_app', 'B')
B.objects.all().delete()
A.objects.all().delete()
And it worked without problems and I could revert the migration!! But, according to Django documentation, this should not be used.
Any ideas about why this happens?