0

What is the best way to iterate from an array of objects and use that data to update selected rows in a database table ?

I wanted to update data from the database where id = tasklist,

id from the json I've provided below, and set attached_document_ins.is_viewed = checked value from the json with that ID .

for example, if id == 35 then attached_document_ins.is_viewed = True cause the checked value of id 35 is True.

What is the best algo for that ?

I have provided my code below.

#Code

def post(self, request):
        data = request.data
        print("Response Data :" , data)
        try:


            attached_document_ins = DocumentTask.objects.filter(id=tasklist_id)
            for attached_document_ins in attached_document_ins:
                attached_document_ins.is_viewed = True
            attached_document_ins.save()
            return Response("Success", status=status.HTTP_200_OK)
        except DocumentTask.DoesNotExist:
            return Response("Failed.", status=status.HTTP_400_BAD_REQUEST)

Json(data)

{
   'tasklist':[
      {
         'files':[

         ],
         'checked':True,
         'company':6,
         'task':'s',
         'applicant':159,
         'id':35
      },
      {
         'files':[

         ],
         'checked':True,
         'company':6,
         'task':'ss',
         'applicant':159,
         'id':36
      },
      {
         'files':[

         ],
         'checked':True,
         'company':6,
         'task':'sss',
         'applicant':159,
         'id':37
      }
   ]
}

1 Answer 1

1

Here is one way you could do it:

for task in data['tasklist']:
    if task['checked']:
        document = DocumentTask.objects.get(id=task['id'])
        document.is_viewed = True
        document.save()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.