Django将单个记录作为JSON返回 [英] Django return a single record as JSON
问题描述
我创建了一个表单,用于在我们的网络管理员中添加有关客户的注释。我正在使用jQuery和Ajax提交。我希望Django视图返回新增的笔记/记录,以便我可以将其附加到客户备注表中。我的Ajax发送正在工作,笔记被保存,我无法显示结果。
I created a form for adding notes about a customer in our web admin. I am using jQuery and Ajax to submit the for. I would like the Django view to return the newly added note/record so I can append it to the customer notes table. My Ajax send is working, and the note is being saved, I just can't display the result.
我已经尝试了以下3行(单独):
I have tried the following 3 lines (separately):
serializers.serialize("json", Note.objects.get(id=new_note.id))
serializers.serialize("json", new_note)
return HttpResponse(simplejson.dumps(new_note), mimetype='application/javascript')
前两个产生:
'Note' object is not iterable
第三个给了我:
<Note: Note object> is not JSON serializable
我真的不在乎我在哪种格式我返回对象,只要我可以使用jQuery接收和显示记录的每个字段。
I don't actually care in which format I return the object, as long as I can receive and display each field of the record using jQuery.
谢谢。
推荐答案
从文档:
serialize函数的参数是将数据序列化的格式(请参阅序列化格式)和序列化的QuerySet。
The arguments to the serialize function are the format to serialize the data to (see Serialization formats) and a QuerySet to serialize.
使用 filter()
而不是 get()
。
这篇关于Django将单个记录作为JSON返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!