-1

I have a json object contaning currencies as listed below which I need to convert it into my model and save it into the DB. Also is there a way to save the list of models in one go?

   {
  "results": {
    "ALL": {
      "currencyName": "Albanian Lek",
      "currencySymbol": "Lek",
      "id": "ALL"
    },
    "KWD": {
      "currencyName": "Kuwaiti Dinar",
      "id": "KWD"
    },
    "LSL": {
      "currencyName": "Lesotho Loti",
      "id": "LSL"
    },
    "MYR": {
      "currencyName": "Malaysian Ringgit",
      "currencySymbol": "RM",
      "id": "MYR"
    },
    "MUR": {
      "currencyName": "Mauritian Rupee",
      "currencySymbol": "₨",
      "id": "MUR"
    }
  }
}

I tried this :

for key,value in currencies.results :
                #print(currency)
                #print(value)   

However, I get the following error :

"Too many attribures to unpack, expected 2

Can someone help me with this?

Paras
  • 3,191
  • 6
  • 41
  • 77

2 Answers2

3

I think it should be like this:

results = currencies.get('results')

for key, value in results.items():  # for python3
    print(key, value)

for key, value in results.iteritems():  # python2.7
    print(key, value)
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • This worked, I can't accept this answer since 10 minutes have not been surpassed, could you also answer the second part, how to instatiate a model and save it in db in one go instead of calling save inside the for loop? – Paras Jan 23 '19 at 08:11
  • Use `MyModel.objects.create(field_name=value)` or if you a dictionary then Use `MyModel.objects.create(**your_dictionary)` – ruddra Jan 23 '19 at 08:13
  • is there a difference between the two, basically I'll be required to create a dictionary that matches the model, or should I directly use MyModel.objects.create(field_name=value) , which one is more efficient? – Paras Jan 23 '19 at 08:21
  • they are the same. Using `**` means it will unpack the dictionary and make it like `key = value`. – ruddra Jan 23 '19 at 08:23
0

You should iterate as

for result in results:
    for currency in result:
        print(result)
Jorge Lavín
  • 937
  • 8
  • 22