1π
β
The easier way to do that is using serialization native from Django.
from django.core import serializers
class Exercise(models.Model):
name = models.CharField(null=False,max_length=255)
def __unicode__(self):
return str(self.id)
serialized_data = serializers.serialize("json", Exercise.objects.all(), fields=('name'))
Making your custom class return JSON
from json import dumps
class ExercisesObject:
def __init__(self, aScore, aExercises):
self.score = aScore
self.exercises = [{e.id: e.name} for e in aExercises]
def json(self):
return dumps({'score': self.score, 'exercises': self.exercises})
π€Mauro Baraldi
1π
You can provide custom json encoder which is subclass of json.JSONEncoder
:
class Exercise:
def __init__(self, value):
self.value = value
self.name = 'soem name'
import json
class CustomEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Exercise):
return {'value': o.value, 'name': o.name}
return super(CustomEncoder, self).default(o)
obj = {
'exercises': [
Exercise(16),
Exercise(1),
Exercise(177),
Exercise(163),
Exercise(291),
Exercise(209)
],
'score': 16.0
}
print(json.dumps(obj, cls=CustomEncoder, indent=4))
output:
{
"exercises": [
{
"name": "some name",
"value": 16
},
...
],
"score": 16.0
}
π€falsetru
Source:stackexchange.com