1

I have a model Example with 3 fields.

class Example(models.Model):
      name = models.CharField(max_length=200, null=False, blank=False)
      number = models.CharField(max_length=200, null=False, blank=False)
      address = models.CharField(max_length=200)`

I have a Post API (rest framework). This would have array of objects. I want to parse this array and store each object in my database. This is the Views.py

class PostExample(APIView):
    def post(self, request, format=None):
        example_records = request.POST["example_data"]
        print example_records

Here "example_data" is the key and value will be an array. Example value:

[
  {
    "name": "test",
    "address": "address",
    "number": 123456789
  },
  {
    ...
  }
] 

I am unable to loop through "example_records". "example_records" prints the array but not able to get each object from this. How to achieve this ??

1
  • use json module Commented May 9, 2017 at 7:04

2 Answers 2

1

You can use json module here. First convert your example_records string data into json object and then parse Example value and finally iterate through all.

import json
data = '''{"Example value":[{"name":"test1","address":"address1","number":123456789},{"name":"test2","address":"address2","number":123456789}]}'''
jobject = json.loads(data)
for val in jobject['Example value']:
    print(val)

{'address': 'address1', 'name': 'test1', 'number': 123456789}
{'address': 'address2', 'name': 'test2', 'number': 123456789}

Then you can simply extract values by passing its corresponding key, For example :

print(val['name'])
'test1'
'test2'
Sign up to request clarification or add additional context in comments.

Comments

0

request.POST is the raw data received during POST, which is a json string. You could use the json module as suggested by some users but Django Rest Framework does the work for you: request.data. That is the whole point of using a framework like DRF.

class PostExample(APIView):
    def post(self, request, format=None):
        example_records = request.data["example_data"]
        for record in example_records:
            ...

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.