Reputation: 2017
I am having a django app in which I am storing the json variable.I have stored the json variable through admin and I am trying to print it in shell.My main aim is to pass this variable to a webpage with ajax method.But first when I was trying to print it in shell I get this error
__str__ returned non-string (type list)
My models.py is of this form
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
# Create your models here.
class newgrid(models.Model):
data = JSONField()
def __str__(self):
return self.data
My JSON variable is of this form
[{"col":1,"row":1,"size_x":1,"size_y":1},{"col":2,"row":1,"size_x":1,"size_y":1},{"col":3,"row":1,"size_x":1,"size_y":1},{"col":4,"row":1,"size_x":1,"size_y":1},{"col":1,"row":2,"size_x":1,"size_y":1},{"col":2,"row":2,"size_x":1,"size_y":1},{"col":3,"row":2,"size_x":1,"size_y":1},{"col":4,"row":2,"size_x":1,"size_y":1},{"col":1,"row":3,"size_x":1,"size_y":1},{"col":2,"row":3,"size_x":1,"size_y":1},{"col":3,"row":3,"size_x":1,"size_y":1},{"col":4,"row":3,"size_x":1,"size_y":1},{"col":5,"row":1,"size_x":1,"size_y":1}]
In shell I ran following commands
from testforweb.models import newgrid
newgrid.objects.all()
It initially returned this
<QuerySet [<newgrid: newgrid object (1)>]>
But then I added
def __str__(self):
return self.data
Just to see the actual JSON variable.But I am getting the error How to see the actual JSON variable which I inserted through admin coz I need to send it to webpage as it is
Edit 1
My updated models.py
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
import simplejson as json
# Create your models here.
class newgrid(models.Model):
data = JSONField()
def __str__(self):
json.dumps(self.data)
Upvotes: 1
Views: 1287
Reputation: 1511
Use
def __str__(self):
return '%s' % (self.data)
Instead of
def __str__(self):
return json.dumps(self.data)
Upvotes: 1
Reputation: 3100
The __str__
function must return a string:
def __str__(self):
return json.dumps(self.data)
Upvotes: 3
Reputation: 7332
The JSON field will actually decode the JSON into native python types (lists and dictionaries).
The __str___
method is always expected to return a string.
If you want a string representation of the json, you should use json.dumps(self.data)
or similar to serialise the data field as the return value of __str__
.
Upvotes: 1