在迁移过程中如何调用django模型类的静态方法 [英] How to call a static methods on a django model class during a south migration
问题描述
类帐户(models.Model):
pre>
name = models.CharField()
@staticmethod
def lookup_by_name(name):
#实际上比这个
返回Account.objects.get(name = name)
class Record(models.Model):
account_name = models.CharField()
acct = models.ForeignKey('Account')
...
类迁移(DataMigration):
def forward(self,orm):
#将具有错误FK的记录修正为帐户
,用于在orm.Record.objects.all()中记录:
记录.acct = orm.Account.lookup_by_name(record.account_name)
record.save()
但是这个失败了
AttributeError:type object'Account'没有属性'lookup_by_name'
我猜南非只是不支持ort
@staticmethod
在模型类?
尝试导入帐户直接失败,除非我也直接导入记录,完全忽略ORM对象。这是一个安全的选择,因为它是一个数据迁移,而且架构没有改变?或者我应该手工运行这个修复,而不是在南移的上下文中。
解决方案你不能使用方法从south.py迁移中的models.py。原因是在将来,models.py将会发展,迟早会删除这些方法,那么迁移将被破坏。
你应该把所有的代码都需要迁移文件本身。
I'm writing a data migration in south to fix some denormalized data I screwed up in earlier code. The way to figure out the right value for the incorrect field is to call a static method on the django model class. The code looks like this:
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()
But this fails with
AttributeError: type object 'Account' has no attribute 'lookup_by_name'
I'm guessing south just doesn't support
@staticmethod
s on model classes?Trying to import Account directly fails, unless I also import Record directly and completely ignore the ORM object. Is that a safe option, since it's a data migration and the schema isn't changing? Or should I just run this fix by hand rather than in the context of a south migration.
解决方案You can't use methods from models.py in south migrations. The reason is that in the future models.py will evolve and sooner or later you will delete those methods, then migration will be broken.
You should put all code needed by migration in migration file itself.
这篇关于在迁移过程中如何调用django模型类的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!