我在我的应用程序中添加了一个模型,它通过一对一的字段Target
标记一个Revision
对象(来自)。django-reversion
标签取决于版本集中的对象,如果这些对象中的任何一个需要标签,则应为整个修订设置标签。我正在尝试使用django-south
数据迁移来遍历Revision
数据库中的所有对象,检查关联中的每个对象version_set
,并在必要时设置标签。
class Migration(DataMigration):
def forwards(self, orm):
for revision in orm["reversion.Revision"].objects.all():
try:
revision.target # the revision is already tagged
except: # revision.target raises different sorts of DoesNotExist errors,
# and I can't work out how to catch all of them
for version in revision.version_set.all():
try:
tag = version.object.get_tag() # all models in my app that
orm.Target.objects.create( # specify tags have this method
revision=revision,
tag=tag)
break
except AttributeError: # the version set doesn't contain any
pass # models that specify a tag
给出一个错误:
[... lots of stuff cut ...], line 21, in forwards
for version in revision.version_set.all():
AttributeError: 'Revision' object has no attribute 'version_set'
如何在不同应用程序的数据迁移期间访问对象的version_set
?Revision
编辑感谢丹尼尔,我走得更远了。在以下代码中,我尝试通过 Migration's own 访问所有模型orm
:
def forwards(self, orm):
my_models = { # models with a .get_tag() method
"modela": orm.ModelA,
"modelb": orm.ModelB,
}
for revision in orm["reversion.Revision"].objects.all():
for version in orm["reversion.Version"].objects.filter(revision=revision):
try:
model = my_models[version.content_type.model]
instance = model.objects.get(id=version.object_id)
tag = instance.get_tag()
orm.RevisionTargetLanguage.objects.create(
revision=revision,
tag=tag)
break
except KeyError: # not one of the models with a .get_tag() method
pass
instance = model.objects.get(id=version.object_id_int)
除了例外,这都失败了DoesNotExist: ModelB matching query does not exist
。