Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 484
Damith Ganegoda Avatar asked Jan 16 '16 10:01

Damith Ganegoda


People also ask

How use JSON field in Django model?

Many a time, on developer website, we need to add developer data and JSON fields are useful in such cases. First create a Django project and an app. Please do all the basic things, like adding app in INSTALLED_APPS and setting up urls, making a basic model and render its form in an HTML file.

How do I convert JSON to Python?

Parse JSON - Convert from JSON to PythonIf you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

Can we convert JSON to DataFrame in Python?

You can convert JSON to Pandas DataFrame by simply using read_json() . Just pass JSON string to the function. It takes multiple parameters, for our case I am using orient that specifies the format of JSON string. This function is also used to read JSON files into pandas DataFrame.

Does Django support JSON?

Thanks to Django's native support for jsonb , you can get started using JSON data in your web applications without learning all the native Postgres query operators. Next time you need more flexibility in your data model and want to benefit from the strengths of Postgres give jsonb fields a try.

How do I use JSON in Django templates?

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:

What is the use of Django in Python?

Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models Data Into Json Data In Django ?

How do I convert a Django model to SQL?

Django uses ORM (Object-relational mapping). hence a models.Model instance will be translated to SQL by 'manage.py makemigrations' command. so you can see if the database you work with has this field.

How do I import data directly from Django admin?

The django-import-export library works with the concept of Resource, which is class definition very similar to how Django handles model forms and admin classes. If you want to handle data directly from Django admin then you should put the code inside the admin.py file.


1 Answers

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()}
like image 98
bakkal Avatar answered Oct 13 '22 12:10

bakkal