一次更新多个对象

时间:2015-06-30 10:53:51

标签: django django-views

我有一个函数应该将用户创建的所有对象更新为非活动状态。所以我编码了这个:

def TurnOff(request, passed_id):
    if request.user.is_authenticated():

        #this should set all objects to an inactive state
        tmp = myModel.objects.filter(created_by=request.user).update(active=False)

        #this is to set one specific object to an active state again
        myModel = get_object_or_404(myModel, created_by=request.user, pk=passed_id)
        tmp = myModel.objects.filter(created_by=request.user, pk=passed_id).update(active=True)

        return HttpResponseRedirect("../started")

    else:
        return HttpResponseRedirect("/")

tmp = myModel.objects.filter(created_by=request.user).update(active=False)不起作用(这意味着假未设置),只有当我使用附加关键字pk=ANY_ID指定过滤器时,我才想更新所有对象,如docs

2 个答案:

答案 0 :(得分:4)

在这种情况下,请替换以下行

tmp = myModel.objects.filter(created_by=request.user, pk=passed_id).update(active=True)

以下内容:

tmp.active = False
tmp.save()

<强> EDITED

因为&#39; tmp&#39;是myModel的一个对象,它只返回一个对象,因为你使用pk来检索它。

答案 1 :(得分:0)

更改

# after this line myModel is not Model anymore, but instance of myModel
# with created_by=request.user and pk=passed_id
myModel = get_object_or_404(myModel, created_by=request.user, pk=passed_id)
# so this line doesn't work
tmp = myModel.objects.filter(created_by=request.user, pk=passed_id).update(active=True)

# you want to update _one_ instance, don't you?
tmp = get_object_or_404(myModel, created_by=request.user, pk=passed_id)
tmp.active = True
tmp.save()