有没有办法像访问当前对象一样访问 django-reversion 对象?

Is there a way to access a django-reversion object as if it were the current object?

我正在使用 Django-Reversion - 有没有办法暂时恢复对象的先前版本,以便可以在 DetailView 中查看它?

非工作代码 - version.get_object() 会很好..

class ProductDetailView(DetailView):

    def get_object(self):
        obj = super(ProductDetailView, self).get_object()
        if self.request.GET.get('v') is not None:
            version_id = force_text(self.request.GET.get('v'))
            version = get_object_or_404(Version, pk=version_id, object_id=force_text(obj.pk))
            return version.get_object()
        return obj

从我的 post @ http://spapas.github.io/2015/01/21/django-model-auditing/#using-django-reversion

复制

[...] 每个版本都有对应修订版的 revision 属性,可用于执行以下操作:

  • 获取通过 revision.user 属性进行更改的用户
  • 通过revision.date_created属性获取变化的日期
  • 使用 field_dict 属性
  • 获取对象字段的值,因为它们在此修订版中
  • 使用 object_version.object 属性
  • 获取该版本上的模型实例
  • 使用 revert() 方法恢复到该对象的先前版本

所以尝试将 return version.get_object() 行更改为 return version.object_version.object!

更新以回答 OP 对相关对象的评论:django-reversion 支持对模型进行分组更改的修订——从 http://django-reversion.readthedocs.org/en/latest/api.html#creating-revisions

复制

A revision represents one or more changes made to your models, grouped together as a single unit. You create a revision by marking up a section of code to represent a revision. Whenever you call save() on a model within the scope of a revision, it will be added to that revision.

因此,如果您在单个 POST 请求中更改所有模型,您可以将其添加到修订版中,使所有更改的对象成为该修订版的成员。之后,当您拥有对象的一个​​版本时,您可以使用它的还原来获取属于 same 修订版的所有对象的所有版本:version.revision.version_set.all().

如果你在保存主对象时实际上没有保存相关对象,那么相关对象不属于修订版,那么是的,你需要去兔子洞并获得修订版相关对象,因为它们在主要对象修订日期(这是一个相当复杂的查询)。

我想你的问题已经解决了,但只是为了记录,你可以使用 version._object_version.object 访问实例,但它将具有最新版本的反向关系信息。

似乎获得包括关系数据在内的完整实例的唯一方法是启动一个事务,恢复修订,做任何你需要做的事情并撤销事务,正如作者在这里所说:https://groups.google.com/d/msg/django-reversion/FIi8smbLGEc/BvLN20p4HAAJ.