python - 使用模型在 Django 中创建 JSON 响应

标签 python django json django-models django-serializer

我在这里遇到了一些问题。我正在尝试返回由消息和模型实例组成的 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)

那行得通...有什么区别?!

谢谢!

最佳答案

你应该使用 django serializers而不是 simplejson:

例如,这将返回正确序列化的数据:

from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('json', some_queryset)
# serialize object
serialized_object = serializers.serialize('json', [some_object,])

关于python - 使用模型在 Django 中创建 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12553599/

相关文章:

python - Django 如何循环对象并在模板中显示变量

python - Ubuntu 为 Django 设置环境变量

c# - WCF Web 服务与 MySQL,读取 SQL 数据时出错?

python - 将 Subprocess.call 的输出存储在字符串中

python - 使用 XPATH 从特定表/网站获取数据

c++ - 在 vb6 中创建的 "standard"dll 在 python 中调用时会出现访问冲突

c - 删除 R/C 中的字节顺序标记

Python - 如何找到文件中的行位置,并围绕该行移动?

python - Django CBV - 如何避免为每个 View 重复 get_context_data 以获得自定义标题?

php - JSON并上传图片到服务器