Skip to content Skip to sidebar Skip to footer

How To Save A List Of Dictionaries As Each Object In A Django Database Model's Field?

I will make the question I asked (How to store a dictionary in a Django database model's field?) better understood: I got this dictionary sample_dict = [ {'sale_id': 14, 'name'

Solution 1:

Everytime you run your code, new objects will be created, regardless if they are in the DB already or not. You do not provide a unique ID.

To remove ALL objects you can simply run

Creditos1.objects.all().delete()

to check if data is already in the Database to avoid adding it multiple times, you can for example use a shortcut

credit, created = Creditos1.objects.get_or_create(name=..., sale_id=...)

Edit: Some Tricks (offtopic)

Btw. if you loop over a list in python there is a shorter way to do so:

for item in h:
    Creditos1.objects.create(name=item['name'], sale_id=item['sale_id'] ...)

and if the keys are exactly the same as the arguments you want to pass, you can automatically unpack them using

for item in h:
    Creditos1.objects.create(**item)

Putting all together:

after running the delete command or (re)moving the sqlite file, this should avoid storing the same data multiple times.

# models.pyclassCreditos1(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)


# view or script

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}
]


for item in sample_dict:
    c, new = Creditos1.objects.get_or_create(**item)
    # optional:ifnot new:
        print("Entry already in the DB:")
        print(c)

Post a Comment for "How To Save A List Of Dictionaries As Each Object In A Django Database Model's Field?"