0

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'
3
  • 1
    is this a once in a lifetime thing? if so write a script with a for loop go though every entry of the json, get the values and create an object Persons.objects.create(rank=rank_value... Commented Jul 29, 2020 at 14:05
  • Does this answer your question? JSON data convert to the django model Commented Jul 29, 2020 at 14:14
  • Sorry can u help me I've got troubles when I convert json to django models. How it should look Commented Aug 1, 2020 at 12:15

1 Answer 1

1

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.

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.