如何将Python Dict值保存到SQLite模型?

时间:2012-03-22 05:41:21

标签: python sqlite dictionary

我正在调用返回JSON数据的API。我使用json.loads将JSON解码为Python作为字典。返回的字典是一个有点复杂的嵌套dictonary,也有嵌套列表。

例如:

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

如何将每个值存储到SQLite数据库中,模型定义为:

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)

每项教育都与候选人相关联,该候选人在候选人类别中定义(此处未显示)。

1 个答案:

答案 0 :(得分:2)

您可以在新对象中设置字段,如

# 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()

注意:您的问题中未提及如何获取name外键的数据,因此您也可以设置。