我需要将某些数据从类A
迁移到类B
A类包含一个m2m字段,例如,该字段链接到auth.User
这只是简单地迁移数据,因此我将这些字段从A类添加到B类并创建了迁移文件。然后,我遍历所有A类对象,并将每个对象的字段分配给B类。
到达m2m字段时,我遇到了TypeError: 'ManyRelatedManager' object is not iterable
class A(object):
something = CharField(blehbleh)
something_else = CharField(blehbleh)
thing_to_migrate = models.ManyToManyField('auth.User', related_name='some_name', blank=True)
class_b = models.ForeignKey('class_B_path', related_name='some_name', on_delete=models.SET_NULL) # so A.class_b gets me class B
class B(object):
already_exist_field = CharField(blehbleh)
thing_I_want_to_migrate_here = models.ManyToManyField('auth.User', related_name='some_other_name', blank=True)
related_name
必须是唯一的,因此我在那里设置了新名称。当我修改迁移脚本时
首先是防御
def migrate_lpinvite_to_invite(apps, schema_editor):
ClassA = apps.get_model('appname', 'A')
for obj in ClassA.objects.all():
obj.class_B.thing_I_want_to_migrate_here = obj.thing_to_migrate
obj.save()
然后进行实际迁移
operations = [
migrations.AddField(
model_name='B',
name='thing_I_want_to_migrate_here',
field=models.ManyToManyField(blank=True, related_name='some_other_name', to=settings.AUTH_USER_MODEL),
migrations.RunPython(migrate_to_B)
]
我得到了上面列出的错误。这样迁移相关字段的正确方法是什么?我可以以某种方式直接引用穿透表,而不进行这种数据迁移吗?