python - 将 JSON 对象列表转换为 Django 模型实例

标签 python json django model

我的 json 文件中有大量 JSON 对象。有些对象比其他对象拥有更多的键,但它们都是我拥有的模型类中的字段键。我想知道,迭代每个 JSON 对象以使用该对象中的数据创建模型实例,为该对象不包含的任何字段创建空值的最佳方法是什么?

minerals.json(片段)

[
    {
        "name": "Abelsonite",
        "image filename": "240px-Abelsonite_-_Green_River_Formation%2C_Uintah_County%2C_Utah%2C_USA.jpg",
        "image caption": "Abelsonite from the Green River Formation, Uintah County, Utah, US",
        "category": "Organic",
        "formula": "C<sub>31</sub>H<sub>32</sub>N<sub>4</sub>Ni",
        "strunz classification": "10.CA.20",
        "crystal system": "Triclinic",
        "unit cell": "a = 8.508 Å, b = 11.185 Åc=7.299 Å, α = 90.85°β = 114.1°, γ = 79.99°Z = 1",
        "color": "Pink-purple, dark greyish purple, pale purplish red, reddish brown",
        "crystal symmetry": "Space group: P1 or P1Point group: 1 or 1",
        "cleavage": "Probable on {111}",
        "mohs scale hardness": "2–3",
        "luster": "Adamantine, sub-metallic",
        "streak": "Pink",
        "diaphaneity": "Semitransparent",
        "optical properties": "Biaxial",
        "group": "Organic Minerals"
    },
    {
        "name": "Abernathyite",
        "image filename": "240px-Abernathyite%2C_Heinrichite-497484.jpg",
        "image caption": "Pale yellow abernathyite crystals and green heinrichite crystals",
        "category": "Arsenate",
        "formula": "K(UO<sub>2</sub>)(AsO<sub>4</sub>)·<sub>3</sub>H<sub>2</sub>O",
        "strunz classification": "08.EB.15",
        "crystal system": "Tetragonal",
        "unit cell": "a = 7.176Å, c = 18.126ÅZ = 4",
        "color": "Yellow",
        "crystal symmetry": "H-M group: 4/m 2/m 2/mSpace group: P4/ncc",
        "cleavage": "Perfect on {001}",
        "mohs scale hardness": "2.5–3",
        "luster": "Sub-Vitreous, resinous, waxy, greasy",
        "streak": "Pale yellow",
        "diaphaneity": "Transparent",
        "optical properties": "Uniaxial (-)",
        "refractive index": "nω = 1.597 – 1.608nε = 1.570",
        "group": "Arsenates"
    },
    {
        "name": "Abhurite",
        "image filename": "240px-Abhurite_-_Shipwreck_Hydra%2C_South_coast_of_Norway.jpg",
        "image caption": "Brownish tabular crystals of abhurite from Shipwreck \"Hydra\", South coast of Norway",
        "category": "Halide",
        "formula": "Sn<sub>21</sub>O<sub>6</sub>(OH)<sub>14</sub>Cl<sub>16</sub>",
        "strunz classification": "03.DA.30",
        "crystal symmetry": "Trigonal",
        "group": "Halides"
    },
]

模型.py

from django.db import models

class Mineral(models.Model):
    name = models.CharField(max_length=300, null=True, blank=True)
    category = models.CharField(max_length=300, null=True, blank=True)
    formula = models.CharField(max_length=300, null=True, blank=True)
    crystal_system = models.CharField(max_length=300, null=True, blank=True)
    unit_cell = models.CharField(max_length=300, null=True, blank=True)
    color = models.CharField(max_length=300, null=True, blank=True)
    cleavage = models.CharField(max_length=300, null=True, blank=True)
    crystal_symmetry = models.CharField(max_length=300, null=True, blank=True)
    mohs_scale = models.CharField(max_length=300, null=True, blank=True)
    image_caption = models.CharField(max_length=300, null=True, blank=True)
    image_filename = models.CharField(max_length=300, null=True, blank=True)
    strunz_classification = models.CharField(max_length=300, null=True, blank=True)

    def __str__(self):
        return self.name

最佳答案

hasattrsetattr 对于解决您的问题非常有用。 (docs)

def convert(jsonObject, model):
    modelObject = model()
    for key in jsonObject:
        if hasattr(modelObject, key):
            setattr(modelObject, key, jsonObject[key])

    return modelObject

converted = list()
for item in jsonArray:
    mineral = convert(item, Mineral)
    mineral.save()
    converted.append(mineral)

关于python - 将 JSON 对象列表转换为 Django 模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188070/

相关文章:

java - 是否有 jackson 注释来抑制不必要的 JSON 包装?

javascript - 增加 Django 消息的显示时间

Python:用土耳其语字母阅读和打印土耳其语的问题

python - 创建子目录并根据文件名 PYTHON 对文件进行排序

json - 使用 Bash 变量构建 JSON 字符串

javascript - 是否可以在 ASP.NET MVC4 中使用一个 Controller 函数在 View 中返回两个数组?

python - Django 迁移找不到 GDALRaster

使用 Select2 小部件的 django-autocomplete-light 初始数据

python - 在 windows 7 中为 python 3.5 安装 pywin32

python - 将 txt 转换为 xlsx,同时将数字单元格的单元格属性设置为数字