简体   繁体   中英

How to save Python Dict Values to SQLite Model?

I am calling an API that returns JSON data. I am using json.loads to decode the JSON to Python as a dictionary. The dictionary that returns is a somewhat complex nested dictonary with nested lists as well.

For example:

{ "educations": { "_total": 1, "values": [{ "degree": "Bachelor of Arts", "fieldOfStudy": "Psychology", "schoolName": "Antioch University Seattle" }] }

How do I store each of the values into an SQLite database with the model defined as:

class Educations(models.Model):
    name = models.ForeignKey(Candidate)
    degree = models.CharField(max_length=200)
    fieldOfStudy = models.CharField(max_length=200)
    schoolName = models.CharField(max_length=200)

Each education is associated with a Candidate which is defined in the Candidate class (not shown here).

You can set the fields in new object like

# Get after json.dump
json_data = { "educations": { "_total": 1, "values": [{ "degree": "Bachelor of Arts", "fieldOfStudy": "Psychology", "schoolName": "Antioch University Seattle" }] }

for each_education in json_data['educations']['values']
    new_education = Education(**each_education)
    # Set the name foreign key
    # new_educaiton.name = name
    new_education.save()

Note: How you will get the data for the name foreignkey is not mention in your question so that also you can set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM