2014-03-28 57 views
0

我在我的应用中添加了一个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' 

我怎样才能在不同的应用程序一个datamigration期间获得访问Revision对象version_set

编辑感谢丹尼尔我进一步。在下面的代码我尝试通过访问所有车型迁移自己的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 

这种失败在与例外DoesNotExist: ModelB matching query does not existinstance = model.objects.get(id=version.object_id_int)

回答

1

你可以尝试

orm['reversion.Version'].objects.filter(revision=revision) 
+0

这让我在正确的方向。我收到了一个错误:“应用程序”reversion“中的'model'版本在此迁移中不可用。我向数据迁移实例的models属性添加了'version'(来自http://stackoverflow.com/questions/19400149/django -south-how-can-i-access-models-in-sub-packages-in-migrations),但是我想我有一个类似的问题:version.object.get_tag()调用总是引发一个AttributeError - 推测因为由version.object表示的对象不可用。 –