Foriegn key returning DoesNotExist after schemamigration

51 views Asked by At

When I first started out with Django I foolishly created a model (lets call it Foo) and explicitly give it a id field not knowing that django added this automatically. I also have a model (lets call it Bar) with a foreign key to this model. I wanted to update things and get rid of this foo_id field so I deleted it, ran a schemamigration with south and ran the change. Problem I'm getting now is my Bar model is throwing errors with DoesNotExist: Foo matching query does not exist. when I try to call foo from it

If I look at the object, there is an attribute for foo and foo_id. foo_id returns a ID but when I just try to call foo, for 95% of them it returns the error.

class Foo(models.Model):
    foo_id = models.IntegerField(primary_key=True)

class Bar(models.Model)
    foo = models.ForeignKey(Foo)

The schemamigration

class Migration(SchemaMigration):                                                                          

    def forwards(self, orm):                                                                               
        # Deleting field 'Foo.foo_id'                                                                  
        db.delete_column(u'foo', 'foo_id')                                                             

        # Adding field 'Foo.id'                                                                          
        db.add_column(u'foo', 'id',                                                                      
                      self.gf('django.db.models.fields.AutoField')(default=None, primary_key=True),        
                      keep_default=False)                                                                  
1

There are 1 answers

0
Kevin Cherepski On

What needed to be done was a data transformation within the migration file, which required some customization

class Migration(SchemaMigration):                                                                          

    def forwards(self, orm):
        # Adding field 'Foo.id'                                                                          
        db.add_column(u'foo', 'id',                                                                      
                      self.gf('django.db.models.fields.AutoField')(default=None),        
                      keep_default=False)

        for bar in Bar.objects.all():
            bar.foo_id = bar.foo.id
            bar.save()

        # Deleting field 'Foo.foo_id'                                                                  
        db.delete_column(u'foo', 'foo_id')

        db.create_primary_key('food', 'id')                                                             

It's really untested but probably close to what is needed.