Nurbek
Nurbek

Reputation: 7

Load json data list in Django models

I'm tring to convert this json list to django models. but I'm confused. How can I solve this question: Json

[
  {
    "rank": 1,
    "employer": "Walmart",
    "employeesCount": 2300000,
    "medianSalary": 19177
  },
  {
    "rank": 2,
    "employer": "Amazon",
    "employeesCount": 566000,
    "medianSalary": 38466
  }
]


class Persons(models.Model):
    rank = models.PositiveIntegerField()
    employer = models.CharField(max_length=100)
    employeesCount = models.PositiveIntegerField()
    medianSalary = models.PositiveIntegerField()

    verbose_name = 'Person'
    verbose_name_plural = 'Person'

Upvotes: 0

Views: 137

Answers (1)

Sadan A.
Sadan A.

Reputation: 1107

There are multiple ways to achieve this.

  1. You can either write some sort of script or management command and load data in the database.
  2. Have you looked at the loaddata command? I am not sure if you can edit this JSON, if you can change your JSON to something like below and put it in a folder with name fixtures within the app and run command python manage.py loaddata <name_of_file> will load all of this data to the specified model
[
  {
    "model": "app_name.person",
    "fileds": {
       "rank": 1,
      "employer": "Walmart",
      "employeesCount": 2300000,
      "medianSalary": 19177
    }
  },
  {
    "model": "app_name.person",
    "fileds": {
      "rank": 2,
      "employer": "Amazon",
      "employeesCount": 566000,
      "medianSalary": 38466
    }
  }
]

I don't know if 2nd option is feasible for you but the first option would definitely work.

Upvotes: 1

Related Questions