Silvio Aranda
Silvio Aranda

Reputation: 37

How to store a dictionary in a Django database model's field?

I want to store this list of dictionarys in a Django database:

h =  [

{'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 3, 11),
  'debe': 500.0},
 {'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 4, 11),
  'debe': 500.0},
 {'sale_id': 15,
  'name': 'Yamila',
  'fecha': datetime.date(2021, 4, 14),
  'debe': 2000.0}

] 

I've tried this:

h = tabla_creditos()

class Creditos1(models.Model):

    sale_id = models.IntegerField(default=0)
    name = models.CharField(max_length=150)
    fecha = models.DateTimeField(default=datetime.now)
    debe = models.IntegerField(default=0)

for i in range(0,len(h)):
    Creditos1.objects.create(name=h[i]['name'], sale_id=h[i]['sale_id'], fecha=h[i]['fecha'], debe=h[i]['debe'])

where "h" is that dictionary, which results from "tabla_creditos()" function. And then, I tried to create the values for the DB with "objects.create" but I got duplicated values stored in DB:

enter image description here

So, how can I store that dict in the DB?

I found this solution: How to store a dictionary in a Django database model's field but none of the answers helped me.

Thanks!

EDIT With the Rohith answer, I got this:

enter image description here

But I would like something like this, transform every key of the dict in a DB column:

enter image description here

Upvotes: 1

Views: 4577

Answers (2)

Rohith Samuel
Rohith Samuel

Reputation: 311

There are a few ways to save a Dictionary in Models. I am mentioning the use of the JSON Field.

If you are using PostgreSql as your database then you have access to JSON Field. you can read about it in the documentation. This will let you save the dictionary as a JSON File which Django supports

Eg:

from django.contrib.postgres.fields import JSONField

class Creditos1(models.Model):
    dict_info = JSONField(default=dict)

In your Code

sample_dict =  [

{'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 3, 11),
  'debe': 500.0},
 {'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 4, 11),
  'debe': 500.0},
 {'sale_id': 15,
  'name': 'Yamila',
  'fecha': datetime.date(2021, 4, 14),
  'debe': 2000.0}

]

credit = Creditos1.objects.create(dict_info=sample_dict)

If you are using any other databases, I would recommend creating the field as CharField(). Then encode the dict as a JSON string and save that string into Credit. Then you can decode the JSON string back.

Eg:

class Creditos1(models.Model):
    dict_info = CharField(blank=True, null=True)

In your Code:

import json
sample_dict =  [
    
    {'sale_id': 14,
      'name': 'Macarena',
      'fecha': datetime.date(2021, 3, 11),
      'debe': 500.0},
     {'sale_id': 14,
      'name': 'Macarena',
      'fecha': datetime.date(2021, 4, 11),
      'debe': 500.0},
     {'sale_id': 15,
      'name': 'Yamila',
      'fecha': datetime.date(2021, 4, 14),
      'debe': 2000.0}
    
    ]
    encoded_json = json.dumps(sample_dict)
    credit = Creditos1.objects.create(dict_info=encoded_json)

In order to get the values of the the dict, you can use json.loads()

decoded_data = json.loads(credit.dict_info)
print(decoded_data[0]["name"])

UPDATE

From my understanding, The function tabla_creditos() is still unclear and that might be the reason for the multiple objects being created or it can even be that you might not have cleared the Database (Use the code to delete all records Creditos1.objects.all().delete() ).

If you want to Save the list of dictionaries as each object, (Assuming you have a clean DB) Your Code:

h = some_func()
uniquefied_list = list({v['sale_id']:v for v in h}.values())
for x in range(0, len(uniquefied_list)):
    Creditos1.objects.get_or_create(name=h[x]["name"], debe=h[x]["debe"]....)

Here, get_or_create would be a better way to handle this Here is the documetation

Hope this resolves your issue.

Upvotes: 3

dchoruzy
dchoruzy

Reputation: 349

Use JSON Field. note that its not supported in SQLite

Upvotes: 0

Related Questions