我正在尝试向我的模型之一添加一个新字段,我想使用迁移的RunPython为该模块的所有现有实例填充此字段。
问题在于,人口普查正在使用另一个模型的类方法来完成,该方法具有此模型的外键:
class A(mptt_models.MPTTModel):
baz = models.ForeignKey(to='b.B', related_name='aaa', ...)
def get_yun(self):
return "YUN"
class Meta:
app_label = 'b'
class B(models.Model):
foo = ...
yun = models.CharField(...) # This is the new field
class Meta:
app_label = 'b'
我的迁移文件包含以下功能,该功能是在migrations.RunPython
操作之后使用migration.AddField
调用的:
def set_yun(apps, schema_editor):
B = apps.get_model("b", "B")
for b in B.objects.all()
b.yun = b.aaa.first().get_yun()
最后一行抛出AttributeError: 'A' object has no attribute 'get_yun'
我读过类似的问题,并且我知道apps.get_model
返回的浅表模型不包含我在模型类中声明的方法。
但是,没有一个答案对我有用(看起来它们与django的较新版本有关-我正在使用1.8
)
是否可以通过迁移文件使用RunPython来填充我的新字段,或者在修改模型后必须手动进行操作?