I'm trying to iterate and append the QId
and Answer
from the payload, desired output expected would be like 12|Yes&&13|Yes&&14|Yes&&15|Yes&&16|Yes&&17|Yes&&
.
All I wanted is to concatenate QId
and Answer
before it saves to the database. How could I achieve this
Qstans = str(qid) '|' answer '&&'.join([str(qid) '|' (answer) for ran in request.data])
this line which append the values
output which I'm getting
12|Yes12|Yes&&12|Yes&&12|Yes&&12|Yes&&12|Yes&&12|Yes
payload:
0: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 150…}
1: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 151…}
2: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 152…}
3: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 153…}
4: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 154…}
5: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 155…}
6: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 156…}
code here:
@api_view(['POST'])
def SaveUserResponse(request):
if request.method == 'POST':
for ran in request.data:
qid = ran.get('QId')
answer = ran.get('Answer')
Qstans = str(qid) '|' answer '&&'.join([str(qid) '|' (answer) for ran in request.data])
print(Qstans)
CodePudding user response:
You're using a list comprehension within a loop, which is unnecessary for (what I understand is) your goal. Within the comprehension, you're also using variables that you assigned in the loop, leading to all the Q/A values being 12 and "Yes" respectively.
Simply swapping out the loop and using:
if request.method == 'POST':
Qstans = '&&'.join(str(ran.get('QId')) '|' str(ran.get('Answer')) for ran in request.data)
should be sufficient.
I haven't been able to test this because you haven't provided a Python object as mozway mentioned in the comments, but this should work with maybe minor tweaks (such as appending a '&&'
in case you require it).
CodePudding user response:
There seems to be double iteration, so you could try this code instead
@api_view(['POST'])
def SaveUserResponse(request):
if request.method == 'POST':
Qstans = ""
for ran in request.data:
qid = ran.get('QId')
answer = ran.get('Answer')
Qstans = Qstans str(qid) '|' answer '&&'
print(Qstans)
notice how the print(Qstans) is outside the loop