Damith Ganegoda Damith Ganegoda - 7 days ago 4x
JSON Question

JSON data convert to the django model

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()

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


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()}