我正在编写一个小型数据迁移,为没有UserProfiles的现有Django用户创建UserProfiles。
def forwards(self, orm):
"Write your forwards methods here."
for user in User.objects.all():
try:
person = user.get_profile()
except:
newperson = orm.Person(user=user)
newperson.save()
但我一直收到
"Person.user" must be a "User" instance
我做错了什么?
在South编写迁移时,不必直接使用模型类,而是使用冻结的模型类。在上面的示例中,您可能试图将当前User对象分配给冻结的Person。冻结的Person对象需要一个冻结的User。
你需要重写如下:
def forwards(self, orm):
"Write your forwards methods here."
for user in orm['auth.User'].objects.all():
try:
# cannot use user.get_profile() because it is not available in the frozen model
person = orm.Person.get(user=user)
except:
newperson = orm.Person(user=user)
newperson.save()
请参阅http://south.readthedocs.org/en/latest/ormfreezing.html#accessing-orm
顺便说一句,我建议您不要使用除之外的裸,而是除SomeException以外的以更健壮。