0

对于我的 django1.4 应用程序,我正在尝试使用南进行数据迁移。我正在使用 postgres8.3

我有一个MyCategory模型,我需要为其添加一个名为creatordjango.contrib.auth.models.User的字段

我修改了类并添加了字段

from django.contrib.auth.models import User
class MyCategory(models.Model):
    name=models.CharField(unique=True,max_length=50)
    description=models.TextField(blank=True)
    creator = models.ForeignKey(User,null=True)#added
    slug=models.SlugField(editable=False)

我跑了python manage.py schemamigration myapp --auto

哪个输出+ Added field creator on myapp.MyCategory 并创建了一个文件0003_auto__add_field_mycategory_creator.py

然后我希望所有旧记录都拥有 webapp 的超级用户作为创建者。所以我尝试了数据迁移

我跑了python manage.py datamigration myapp add_creator

这输出了一个文件 add_creator.py 我在其中实现了 forwards 方法,如下所示。(后来我添加了一个 print stmt 用于调试)

def forwards(self, orm):
    from django.contrib.auth.models import User
    suser = User.objects.filter(is_superuser=True)[0]
    # I also tried User.objects.get(is_superuser=True)
    print 'suser=',suser,'of type=',type(suser)
    for category in orm.MyCategory.objects.all():
        category.creator = suser
        category.save()

然后我运行了迁移命令

python manage.py migrate myapp

这输出一个ValueError

Running migrations for myapp:
 - Migrating forwards to 0004_add_creator.
 > myapp:0004_add_creator
suser= damon of type= <class 'django.contrib.auth.models.User'>
Error in migration: myapp:0004_add_creator
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_manager(settings)
....
File "/usr/local/lib/python2.6/dist-packages/south/migration/migrators.py", line 57, in <lambda>
    return (lambda: direction(orm))
  File "/home/me/dev/python/django/myapp/migrations/0004_add_creator.py", line 14, in forwards
    category.creator = suser
  File "/home/me/Django-1.4/django/db/models/fields/related.py", line 366, in __set__
    self.field.name, self.field.rel.to._meta.object_name))
ValueError: Cannot assign "<User: damon>": "MyCategory.creator" must be a "User" instance.

我不明白这里发生了什么..打印语句显示用户damon属于django.contrib.auth.models.User..south期待其他类型?有人可以帮忙吗?

4

1 回答 1

8

首先,您需要冻结django.contrib.auth数据迁移。这可以通过以下方式实现:

python manage.py datamigration myapp add_creator --freeze auth

其次,您将需要通过orm字典正确引用您的对象:

def forwards(self, orm):
    suser = orm['auth.User'].objects.filter(is_superuser=True)[0]
    print 'suser=',suser,'of type=',type(suser)
    for category in orm['myapp.MyCategory'].objects.all():
        category.creator = suser
        category.save()
于 2012-12-14T06:59:50.190 回答