How to return multiple response in Django
I'm trying to return the same response after the loop ends but I couldn't able to find a approach to implement it.
Here, What I have tried and error which I get local variable 'TaskId' referenced before assignment
views.py:
def GetCurrentRunningActivity(UserID):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s',(UserID,))
result_set = cursor.fetchall()
cursor_set = cursor.fetchall()
for row in result_set:
TaskId=row[0]
Number=row[1]
Opened=row[2]
Contacttype=row[3]
Category1=row[4]
State=row[5]
Assignmentgroup=row[6]
CountryLocation=row[7]
Openedfor=row[8]
Employeenumber=row[9]
Shortdescription=row[10]
Internaldescription=row[11]
Additionalcomments=row[12]
TaskName = row[1]
print("Number", Number)
return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype,
"Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation,
"Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription,
"Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK)
return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype,
"Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation,
"Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription,
"Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK)
Something wrong with your looping logic here: you are trying to "return" every time at loops end. Instead you should collect data to a list and then return Response just once like this:
def GetCurrentRunningActivity(UserID):
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s',(UserID,))
result_set = cursor.fetchall()
cursor_set = cursor.fetchall()
data = []
for row in result_set:
TaskId=row[0]
Number=row[1]
Opened=row[2]
Contacttype=row[3]
Category1=row[4]
State=row[5]
Assignmentgroup=row[6]
CountryLocation=row[7]
Openedfor=row[8]
Employeenumber=row[9]
Shortdescription=row[10]
Internaldescription=row[11]
Additionalcomments=row[12]
TaskName = row[1]
print("Number", Number)
data.append({"TaskId": TaskId, "Number":Number,"Opened":Opened,
"Contacttype":Contacttype, "Category1":Category1, "State":State,
"Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation,
"Openedfor":Openedfor, "Employeenumber":Employeenumber ,
"Shortdescription":Shortdescription,
"Internaldescription":Internaldescription,
"Additionalcomments":Additionalcomments,"TaskName":TaskName
})
return Response({"data": data}, status=status.HTTP_200_OK)
And, please, dont forget to follow PEP8