cycle through output and add to database

An API call returns some data that I want to upload into the database, it returns about 5000 records. I only want to run this manually when needed.

[
  {
    "id": "01",
    "symbol": "xyz",
    "name": "xyz"
  },
  {
    "id": "02",
    "symbol": "abc",
    "name": "abc"
  },
  {
    "id": "04",
    "symbol": "fhf",
    "name": "fhf"
  },
  {
    "id": "05",
    "symbol": "gxfg",
    "name": "gxfg"
  },
]

Is there a way I can cycle through each one and upload it to a model? The model will have matching field names os ID Symbol and Name


Solution 1:

I think I might be missing something, but if all you want to do is take that data and create models with it then you can just do this:

dataList = [
  {
    "id": "01",
    "symbol": "xyz",
    "name": "xyz"
  },
  {
    "id": "02",
    "symbol": "abc",
    "name": "abc"
  },
  {
    "id": "04",
    "symbol": "fhf",
    "name": "fhf"
  },
  {
    "id": "05",
    "symbol": "gxfg",
    "name": "gxfg"
  },
]


for index in range(len(dataList)):
    if not YourModel.objects.filter(name=dataList[index]['name']).exists():
        YourModel.objects.create(
            id = int(dataList[index]['id']),
            symbol = dataList[index]['symbol'],
            name = dataList[index]['name'])

This uses the exists() function in django, which can be very fast.