我有一个名为Exercise
的对象,它有很多变量,我只希望为每个Exercise
序列化两个变量:id
和{
我的VAR是这样的:
{'exercises': [<Exercise: 16>, <Exercise: 1>, <Exercise: 177>, <Exercise: 163>, <Exercise: 291>, <Exercise: 209>], 'score': 16.0}
如何将其转化为:
^{pr2}$当我做一个json_dumps(vars(exerciseobject))
时,我显然得到了一个错误TypeError: <Exercise: 16> is not JSON serializable
资料来源:
# Model
class Exercise(models.Model):
name = models.CharField(null=False,max_length=255)
def __unicode__(self):
return str(self.id)
# Object
class ExercisesObject:
def __init__(self, aScore, aExercises):
self.score = aScore
self.exercises = aExercises # Contains an array of Exercise instances.
# Example:
firstExercise = Exercise.objects.get(pk=1)
secondExercise = Exercise.objects.get(pk=5)
aList = [firstExercise,secondExercise]
obj = ExercisesObject(23,aList)
更简单的方法是使用来自Django的serializationnative。在
使自定义类返回JSON
^{pr2}$您可以提供自定义json编码器,它是^{} 的子类:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐