JSON数据转换为Django模型 [英] JSON data convert to the django model
问题描述
我需要将JSON数据转换为Django模型.
I need to convert JSON data to django model.
这是我的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方法
This is my django method
def get_titles():
url = 'http://localhost:8080/titles/'
r = requests.get(url)
titles = r.json()
print(titles['data'])
我需要的是转换为模型并传递给模板.请让我知道如何将JSON转换为模型.
What I need is convert to the model and pass to the template. Please let me know how to convert JSON to Model.
推荐答案
在Django模板中使用JSON
您不必将JSON结构转换为Django模型,仅在Django模板中使用它:JSON结构(Python dict)在Django模板中就可以正常工作
Using JSON in Django templates
You don't have to convert the JSON structure into a Django model just to use it in a Django template: JSON structures (Python dicts) work just fine in a Django template
例如如果将{'titles': titles['data']}
作为上下文传递到模板,则可以将其用作:
e.g. if you pass in {'titles': titles['data']}
as the context to your template, you can use it as:
{% for title in titles %}
ID is {{title.id}}, and name is {{title.name}}
{% endfor %}
只要您不需要使用Django存储数据,上述解决方案就可以正常工作.如果要存储,请阅读以下内容.
As long as you don't need to store the data with Django, the above solution works just fine. If you want to store, read below.
您可以创建一个模型来存储JSON数据.存储后,您可以将查询集传递给模板
You can create a model to store that JSON data in. Once stored you can pass the queryset to your template
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()}
这篇关于JSON数据转换为Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!