我正在南方编写数据迁移,以修复我在早期代码中搞砸的一些非规范化数据。找出错误字段的正确值的方法是在 django 模型类上调用静态方法。代码如下所示:
class Account(models.Model):
name = models.CharField()
@staticmethod
def lookup_by_name(name):
# There's actually more to it than this
return Account.objects.get(name=name)
class Record(models.Model):
account_name = models.CharField()
acct = models.ForeignKey('Account')
...
class Migration(DataMigration):
def forwards(self, orm):
# Fixing Records with the wrong FK to Account
for record in orm.Record.objects.all():
record.acct = orm.Account.lookup_by_name(record.account_name)
record.save()
但这失败了
AttributeError: type object 'Account' has no attribute 'lookup_by_name'
我猜南只是不支持@staticmethod
模型类的 s 吗?
尝试直接导入 Account 失败,除非我也直接导入 Record 并完全忽略 ORM 对象。这是一个安全的选择,因为它是数据迁移并且架构没有改变?或者我应该手动运行此修复程序,而不是在南迁的情况下运行此修复程序。