JSON data convert to the django model

无人久伴 提交于 2019-12-31 23:06:08

问题


I need to convert JSON data to django model.

This is my JSON data

{
  "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"
    }
  ]
}

This is my django method

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

What I need is convert to the model and pass to the template. Please let me know how to convert JSON to Model.


回答1:


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

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 %}

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.

Make a model

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)

or use an UUIDField

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

Store the data in a Django model

# 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'])

Use stored data to pass as template context

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


来源:https://stackoverflow.com/questions/34825875/json-data-convert-to-the-django-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!