上次创建的对象ID

时间:2017-01-23 12:12:46

标签: python django django-queryset

我的ID列是自动递增的,但我必须在创建和保存对象后将ID发送到另一个函数。

actionObj = ScAnsAction()

#actionObj.id -- auto increment

actionObj.user_id = getUserID(request)
actionObj.action_id = 6
actionObj.req_id = request_id
actionObj.a_date = i.strftime("%Y-%m-%d")
actionObj.save()

setUserNotifs(request,#should be latest above objectID)

我在查询集上尝试了最新的功能,但我从列表中删除了列表。

SetUserNotif函数

def setUserNotifs(request,request_id):
    username = request.user.username
    object_id_list = ScAns.objects.filter(username=username).values_list('id',flat=True)
    actionUsers =  ScAnsAction.objects.filter(req_id=request_id).values_list('user_id',flat=True).exclude(user_id=object_id_list).distinct()
    requestCreaterUsername = ScRequests.objects.filter(id=request_id).values_list('sender',flat=True)
    requestCreaterID = ScAns.objects.filter(username=requestCreaterUsername).values_list('id',flat=True)

    # send notification to users who has been commented on that request
    for actionUser in actionUsers:
        actionObj = ScActionNotif()
        actionObj.action_id = request_id
        actionObj.user_id = actionUser
        actionObj.notif = "unread"
        actionObj.save()

    # send notification to the creator of the request
    actionObj = ScActionNotif()
    actionObj.action_id = request_id
    actionObj.user_id = requestCreaterID[0]
    actionObj.notif = "unread"
    actionObj.save()

回溯:

File "/Users/natigvahabov/Desktop/Django/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Users/natigvahabov/Desktop/Django/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/natigvahabov/Desktop/Django/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/natigvahabov/Desktop/Django2/src/profiles/views.py" in addComment
  99.       setUserNotifs(request,actionObj.id)

File "/Users/natigvahabov/Desktop/Django2/src/database/views.py" in setUserNotifs
  136.  actionObj.user_id = requestCreaterID[0]

File "/Users/natigvahabov/Desktop/Django/lib/python2.7/site-packages/django/db/models/query.py" in __getitem__
  295.         return list(qs)[0]

Exception Type: IndexError at /about/addComment/
Exception Value: list index out of range

1 个答案:

答案 0 :(得分:2)

如果您需要actionObj的ID,则应该使用它:

setUserNotifs(request, actionObj.id)