在Django中我有三个模型:
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)
我使用South更改模型以将教练外键添加到播放器:
class Player(models.Model)
team = models.ForeignKey('Team')
coach = models.ForeignKey('Coach')
我在数据迁移中迁移数据:
players = orm.Player.objects.all()
for player in players:
player.coach = player.team.coach
player.save()
当我在数据库中检查数据时,数据迁移得很好(SQLite版本3.7.2):
sqlite> SELECT team_id, coach_id from Player WHERE id = 1;
2|4
但是当我尝试通过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:
几点说明:
这不是实际的代码,但它基本上与它完全匹配。不要求查看实际代码,因为我无法分享它 - 它是保密的,不属于我。但是,我可以使用这个类似的样本提供更多细节。
在我已经创建了迁移之前,我不知道我需要在Player模型上使用coach字段 - 因此我将其手动添加到现有迁移中。我在运行迁移时没有遇到任何错误,并且像我说的那样,迁移似乎在数据库级别正常工作。