我在这里遇到了一些问题。我正在尝试返回由消息和模型实例组成的 JSON 响应:
class MachineModel(models.Model):
name = models.CharField(max_length=64, blank=False)
description = models.CharField(max_length=64, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
added_by = models.ForeignKey(User, related_name='%(app_label)s_%(class)s_added_by')
creation_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
machine_model_model = form.save(commit=False)
r_user = request.user.userprofile
machine_model_model.manufacturer_id = manuf_id
machine_model_model.added_by_id = request.user.id
machine_model_model.save()
alert_message = " The'%s' model " % machine_model_model.name
alert_message += ("for '%s' " % machine_model_model.manufacturer)
alert_message += "was was successfully created!"
test = simplejson.dumps(list(machine_model_model))
data = [{'message': alert_message, 'model': test}]
response = JSONResponse(data, {}, 'application/json')
class JSONResponse(HttpResponse):
"""JSON response class."""
def __init__(self, obj='', json_opts={}, mimetype="application/json", *args, **kwargs):
content = simplejson.dumps(obj, **json_opts)
super(JSONResponse,self).__init__(content, mimetype, *args, **kwargs)
但我不断得到:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <MachineModel: "Test12"> is not JSON serializable
这是为什么?我以前见过:
models = Model.objects.filter(manufacturer_id=m_id)
json = simplejson.dumps(models)
这有效......有什么区别?!
谢谢!