In Django I have three models:
class Player(models.Model)
team = models.ForeignKey('Team')
class Team(models.Model)
name = models.CharField(max_length=20)
coach = models.ForeignKey('Coach')
class Coach(models.Model)
name = models.CharField(max_length=255)
And I change the models using South to add the coach foreign key to the Player:
class Player(models.Model)
team = models.ForeignKey('Team')
coach = models.ForeignKey('Coach')
And I migrate the data in a data migration:
players = orm.Player.objects.all()
for player in players:
player.coach = player.team.coach
player.save()
And the data migrates fine when I check it in the database (SQLite version 3.7.2):
sqlite> SELECT team_id, coach_id from Player WHERE id = 1;
2|4
But when I try to access the data via the Django ORM:
>> player = Player.objects.get(pk=1)
>> player.coach
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call last)
/home/pat/Development/baseball/<ipython console> in <module>()
/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/related.pyc in __get__(self, instance, instance_type)
299 if self.field.null:
300 return None
--> 301 raise self.field.rel.to.DoesNotExist
302 other_field = self.field.rel.get_related_field()
303 if other_field.rel:
DoesNotExist:
A couple of notes:
This is not the actual code, but it is basically an exact match of it. Don't ask to see the actual code because I can't share it - it's confidential and doesn't belong to me. I can, however, provide further details using this analogous sample.
I didn't know that I needed the coach field on the Player model until I had already created the migrations - so I added it to the existing migration manually. I don't get any errors when I run the migration, and, like I said, the migration appears to be working fine at the database level.