如何强制django立即保存,而不是在循环后进行批量更新

时间:2013-11-28 20:04:46

标签: python mysql django django-models persistence

我有这个django views.py方法,旨在将许多数据插入到数据库中。它循环遍历模型数组,如果某个对象尚未在数据库中,则会插入它。

这就是代码的样子:

def update_my_db(request):

    a_models = A_Model.objects.filter(my_flag=True)

    for a_model in a_models:

        b_model_array = []

        [...] # this is where b_model_array gets filled

        for index in range(len(b_model_array)):

            current_b_model = b_model_array[index]

            try:
                b_model = B_Model.objects.get(my_field=current_b_model.my_field)
            except (KeyError, B_Model.DoesNotExist):
                b_model = B_Model.objects.create(field_1=current_b_model.field_1, field_2=current_b_model.field_2)
                b_model.save()

    return HttpResponse(response)

在几次测试之后我注意到db只在最后一次迭代结束时更新,好像django等待对mysql进行批量插入。

问题是:任何迭代都有可能引发异常,使得到目前为止收集的所有数据都因为错误而被丢弃(已经过测试并确认)。当谈到添加400个新行时,在循环#399处引发异常并丢弃所有之前的398行对我来说是非常不受欢迎的。

我知道批处理是关于性能的最佳选择,但这是一个后台例程,所以我并不担心。

Bottomline:有没有办法在每次迭代时强制django更新数据库?

1 个答案:

答案 0 :(得分:2)

如果您使用的是Django 1.6,请查看:https://docs.djangoproject.com/en/dev/topics/db/transactions/

您对该页面的上下文管理器部分感兴趣:

from django.db import transaction

def viewfunc(request):
    # This code executes in autocommit mode (Django's default).
    do_stuff()

    with transaction.atomic():
        # This code executes inside a transaction.
        do_more_stuff()