gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:04:17 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com