python - JSON data convert to the django model -


i need convert json data django model.

this 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 django method

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

what need convert model , pass template. please let me know how convert json model.

using json in django templates

you don't have convert json structure django model use in django template: json structures (python dicts) work fine in django template

e.g. if pass in {'titles': titles['data']} context template, can use as:

{% title in titles %}     id {{title.id}}, , name {{title.name}} {% endfor %} 

as long don't need store data django, above solution works fine. if want store, read below.

make model

you can create model store json data in. once stored can pass queryset template

class title(models.model)     id = models.charfield(max_length=36)     name = models.charfield(max_length=255) 

or use uuidfield

class title(models.model)     id = models.uuidfield(primary_key=true)     name = models.charfield(max_length=255) 

store data in django model

# read json titles = r.json() # create django model object each object in json  title in titles['data']:     title.objects.create(id=title['id'], name=title['name']) 

use stored data pass template context

# pass dict below template context context = {'titles': title.objects.all()} 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -