0

I am a programming self-learner and I am new to python and django and would like to optimize my code.

My problem is that I want to do a get_or_create with some loaded json data. Each dictionary entry is directly linked to my model. example:

data=json.load(file)
Person.objects.get_or_create(
    firstname=data['firstname'],
    surname=data['surname'],
    gender=data['gender'],
    datebirth=data['datebirth'],
)

Are there any ways to automatically link the json properties to my model fields instead of typing all my properties one by one?

pii_ke
  • 2,811
  • 2
  • 20
  • 30
Tibibs
  • 71
  • 1
  • 8

2 Answers2

1

What you might want to do is to unpack your list of arguments. Link to Python docs.

Say your model is Person:

p = Person(**data_dict)
p.save()

Reference

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27
0

You need to write following code in python shell:

import json
data = json.loads(source)
print(json.dumps(data, indent=2))
Akshat Zala
  • 710
  • 1
  • 8
  • 23