JSON data is converted to django model

I need to convert JSON data to a 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'])

I need to convert to a model and go to the template. Please let me know how to convert JSON to Model.

+4
source share
1 answer

Using JSON in Django Templates

You do not need to convert the JSON structure to a Django model to use it in a Django template: JSON structures (Python dicts) work fine in a Django template

eg. if you pass {'titles': titles['data']}as context for your template, you can use it like:

{% for title in titles %}
    ID is {{title.id}}, and name is {{title.name}}
{% endfor %}

Django, . , .

JSON.

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

Source: https://habr.com/ru/post/1624564/


All Articles