1

我在几个脚本中使用了以下实用程序函数:

@transaction.commit_on_success
def save_something(arg):
    # creation of a model_instance using arg
    model_instance.save()

在其中一个脚本中,我将大量这些模型实例上传到数据库。为了提高效率,我尝试这样做:

@transaction.commit_manually
def save_many(arg_list):
    for i,arg in enumerate(arg_list):
        save_something(arg)
        if i%1000==0:
            transaction.commit()

是否commit_manually覆盖commit_on_success
如果没有,我该怎么做?

4

3 回答 3

1

看看这个片段,我认为它以更好的方式处理嵌套提交 http://djangosnippets.org/snippets/1343/

于 2012-03-28T17:59:23.447 回答
0

The short answer is "No", and "you can't". What the decorators (and all they can really do) is wrap the functions they decorate in another function that starts a transaction if necessary, and then calls the original function. That's all the commit_manually decorator's wrapper function does. The commit_on_success decorator adds an automatic commit or rollback depending on the success of the wrapped function. The decorators aren't "runtime flags" that get toggled and that other behaviour then keys off of. They're simply a little boilerplate that gets wrapped around your function, and the commit_on_success decorator's boilerplate will always either commit or rollback.

The source for the decorators can tell you more about the details at hand: https://code.djangoproject.com/svn/django/trunk/django/db/transaction.py

于 2012-03-26T09:41:27.947 回答
0

你可以:

@transaction.commit_on_success
def save_something(arg):
    _save_something(arg)

def _save_something(arg):
    # creation of a model_instance using arg
    model_instance.save()

然后在您确实需要免费装饰器的单一情况下,使用_save_something()...

于 2012-03-26T09:44:23.583 回答