将JSON数据转换为Django模型的示例

polhcujo  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(68)

我需要将JSON数据转换为Django模型。
这是我的JSON数据

{
  "data": [
    {
      "id": "20ad5d9c-b32e-4599-8866-a3aaa5ac77de",
      "name": "name_1"
    },
    {
      "id": "7b6d76cc-86cd-40f8-be90-af6ced7fec44",
      "name": "name_2"
    },
    {
      "id": "b8843b1a-9eb0-499f-ba64-25e436f04c4b",
      "name": "name_3"
    }
  ]
}

字符串
这是我的Django方法

def get_titles():
    url = 'http://localhost:8080/titles/' 
    r = requests.get(url)
    titles = r.json()
    print(titles['data'])


我需要的是将JSON转换为模型的示例并将其传递给模板。请告诉我如何将JSON转换为模型。

tktrz96b

tktrz96b1#

在Django模板中使用JSON

你不必为了在Django模板中使用JSON结构而将其转换为Django模型:JSON结构(Python dict)在Django模板中工作得很好
例如,如果你将{'titles': titles['data']}作为上下文传递给你的模板,你可以将它用作:

{% for title in titles %}
    ID is {{title.id}}, and name is {{title.name}}
{% endfor %}

字符串
只要你不需要用Django存储数据,上面的解决方案就可以很好地工作。如果你想存储数据,请阅读下面的内容。

制作模型

您可以创建一个模型来存储JSON数据。存储后,您可以将查询集传递到模板

class Title(models.Model)
    id = models.CharField(max_length=36)
    name = models.CharField(max_length=255)


或使用UUIDField

class Title(models.Model)
    id = models.UUIDField(primary_key=True)
    name = models.CharField(max_length=255)

将数据存储在Django模型中

# Read the JSON
titles = r.json()
# Create a Django model object for each object in the JSON 
for title in titles['data']:
    Title.objects.create(id=title['id'], name=title['name'])

使用存储的数据作为模板上下文传递

# Then pass this dict below as the template context
context = {'titles': Title.objects.all()}

相关问题