django-reversion在shell中正确保存修订,但在视图中没有

时间:2013-08-01 00:17:06

标签: django django-reversion

我面临的问题与Django reversion does not save revisions made in shell

有些相反

正在使用的版本:

Django: v1.3.1

django-reversion: v1.5.7

我编写了一个可用于保存/放弃对模型所做更改的类:

import reversion, datetime

class Execute:
    model = None
    delete_ids = []
    def __init__(self, model):
            self.model = model
        if not reversion.is_registered(model):
            reversion.register(model)
    def update(self, n):
        id = n.pk
        if len(self.model.objects.filter(pk=id)) > 0:
            m= self.model.objects.get(pk=id)
            if len(reversion.get_for_object(m)) == 1: # Update newly inserted element
                reversion.get_for_object(m).delete() # reversion list only 1 long.
                with reversion.create_revision():
                    m=n
                    m.save()
            else: # Update existing element. reversion list will be at least 2 long
                if len(reversion.get_for_object(m)) == 0: # Add self as first revision.
                    with reversion.create_revision():
                        m.save()
                with reversion.create_revision(): # Add updates
                    m=n
                    m.save()
    def insert(self, n):
        with reversion.create_revision():
            n.pk = None
            n.save()
        return n.pk
    def delete(self, n):
        id = n.pk
        if len(self.model.objects.filter(pk=id)) > 0:
            m=self.model.objects.get(pk=id)
            with reversion.create_revision():
                m.save()
            delete_ids.append(id)
            m.delete()
    def discard(self, n):
        id = n.pk
        if len(self.model.objects.filter(pk=id)) > 0:
            m=self.model.objects.get(pk=id)
            rev=reversion.get_for_object(m)
            if len(rev) == 0:
                return
            if len(rev) == 1: #insert operation, then delete
                m.delete()
            else: #update operation, then revert
                rev[len(rev)-1].revert()
            rev.delete()
        if len(reversion.get_deleted(self.model).filter(object_id=id)) > 0:
            reversion.get_deleted(self.model).get(object_id=id).revert()
    def save(self, n):
        id = n.pk
        if len(self.model.objects.filter(pk=id)) > 0:
            m=self.model.objects.get(pk=id)
            m.save()
            reversion.get_for_object(m).delete()
        if len(reversion.get_deleted(self.model).filter(object_id=id)) > 0:
            reversion.get_deleted(self.model).get(object_id=id).delete()

然后我按如下方式使用它:

> my_execute=Execute(MyModel) m=MyModel.objects.get(pk=id)
> 
> --modify something in m-- 
> my_execute.update(tm)
> 
> --modify something else in m-- 
> my_execute.update(tm)
> 
> --modify something else in m-- 
> my_execute.update(tm)
> 
> my_execute.discard(tm)  <-- Revert m to original 
> or 
> my_execute.save(tm) <-- Save new modifications

当我通过shell运行这些时,这非常有效,但在视图中运行POST请求时不一致。

在调试时,我发现基本上在shell中运行时,每次我的注册模型执行“save()”时,我都会看到列表“reversion.get_for_object(m)”按预期添加新修订版。但是当我通过Django视图运行相同时,列表没有按预期更新,但似乎只在达到视图代码结束时才会发生。

例如:当我更新现有模型时,我希望看到两个条目,如:

>>> reversion.get_for_object(tm)
[]
>>> tm_execute.update(tm)
>>> reversion.get_for_object(tm)
[<Version: QGE__Power Sequencing fix__726__lalitb>, <Version: QGE__Power Sequencing fix__726__lalitb>]
>>> 

但是,当我使用视图执行相同操作时:

from collabgrid.testmatrix.models import Testmatrix, Testcaseinfo, Product
from django.http import HttpResponse
from django.utils import simplejson
import json, pdb, datetime, reversion

class Execute:
    model = None
    delete_ids = []
    def __init__(self, model):
            self.model = model
        if not reversion.is_registered(model):
            reversion.register(model)
    def update(self, n):
        id = n.pk;
        if len(self.model.objects.filter(pk=id)) > 0:
            m= self.model.objects.get(pk=id)
            if len(reversion.get_for_object(m)) == 1: # Update newly inserted element
                reversion.get_for_object(m).delete() # reversion list only 1 long.
                with reversion.create_revision():
                    m=n
                    m.save()
            else: # Update existing element. reversion list will be at least 2 long
                if len(reversion.get_for_object(m)) == 0: # Add self as first revision.
                    with reversion.create_revision():
                        m.save()
                with reversion.create_revision(): # Add updates
                    m=n
                    m.save()
    def insert(self, n):
        with reversion.create_revision():
            n.pk = None
            n.save()
        return n.pk
    def delete(self, n):
        id = n.pk
        if len(self.model.objects.filter(pk=id)) > 0:
            m=self.model.objects.get(pk=id)
            with reversion.create_revision():
                m.save()
            delete_ids.append(id)
            m.delete()
    def discard(self, n):
        id = n.pk
        if len(self.model.objects.filter(pk=id)) > 0:
            m=self.model.objects.get(pk=id)
            rev=reversion.get_for_object(m)
            if len(rev) == 0:
                return
            if len(rev) == 1: #insert operation, then delete
                m.delete()
            else: #update operation, then revert
                rev[len(rev)-1].revert()
            rev.delete()
        if len(reversion.get_deleted(self.model).filter(object_id=id)) > 0:
            reversion.get_deleted(self.model).get(object_id=id).revert()
    def save(self, n):
        id = n.pk
        if len(self.model.objects.filter(pk=id)) > 0:
            m=self.model.objects.get(pk=id)
            m.save()
            reversion.get_for_object(m).delete()
        if len(reversion.get_deleted(self.model).filter(object_id=id)) > 0:
            reversion.get_deleted(self.model).get(object_id=id).delete()


tm_execute=Execute(Testmatrix)

def update_sub_col(request):
    print request
    if request.method == 'POST':
        ret = request.POST
        tm_data = json.loads(request.POST['tm_data'])
        for t in tm_data:
            if(len(Testmatrix.objects.filter(pk=t['id'])) > 0):
                tm = Testmatrix.objects.get(pk=t['id'])
                if tm.os != t['sub_col']:
                    tm.os = t['sub_col']
                    print "BEFORE: ", reversion.get_for_object(tm) # List returns as empty []
                    tm_execute.update(tm)
                    print "AFTER:  ",reversion.get_for_object(tm) # List returns as empty []
                                                                  # but subsequent read has one
                                                                  # revision entry.
    json_response = {
        'ret': 'success'
    }
    return HttpResponse(simplejson.dumps(json_response),mimetype='application/javascript')

我看到后续读取的列表只有一个:

[<Version: QGE__Power Sequencing fix__726__lalitb>] 

此时模型会提交所有修改,无法将其还原。不知道为什么差异,因为我在两种情况下使用相同的代码。

我甚至使用pdb检查

之后的修订列表内容
with reversion.create_revision():
                        m.save()

当我通过视图运行时通过更新函数时它是空的,但是在通过shell提示符调试时正确显示了修订条目。

1 个答案:

答案 0 :(得分:2)

事实证明,混合和匹配的修订创建机制正在咬我(尽管docs另有说法)。

我使用以下技术:

1)中间件:

  • django.middleware.transaction.TransactionMiddleware
  • reversion.middleware.RevisionMiddleware

2)上下文管理器

  • reversion.create_revision()上下文管理器

我删除了中间件设置,只使用了Context Manager,所有内容都在shell和AJAX / views中按预期工作。

编辑:结果我正在做正确的事情。删除修订中间件是根据此thread获得更精细控制颗粒的方法。