[Solved]-JSON data convert to the django 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()}

Leave a comment