Home > database >  How to solve the problem that json type data is loaded from template to string type
How to solve the problem that json type data is loaded from template to string type

Time:04-15

The "content" field is data in json format. But when I check this value in template , it resolves to string. I want to print the value corresponding to teacher from the dictionary below. What's wrong?

[views.py]

    history = History(user=request.user, 
                      study=study,
                      content=study.json())
    history.save()

    test = History.objects.filter(study__id='12')

"content" value stored in DB: {'id': 12, 'is_deleted': False, 'type': 'secondary', 'study_name': 'Math', 'teacher': 'Halen/Lisa', 'team': 'A'}

[html]

{% for test in test %}
    {{ test.content.teacher }}? {{ test.content}}
{% endfor %}

In the case of a dictionary, the desired key value can be called, but since it is a string type, the teacher value cannot be retrieved. What should the teacher do to get the value, which is the key?

CodePudding user response:

From Python convert string dictionary to dictionary, we can use

import json

history = History(user=request.user, 
                  study=study,
                  content=study.json())
history.save()

test = History.objects.filter(study__id='12')

test_content = json.loads(test.content)

OR

You can directly do json.loads() in the field using template tags as mentioned here.

CodePudding user response:

You can use literal_eval if properties are with sing quotes:

import ast

...

test.content = ast.literal_eval(test.content)
  • Related