Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django return a single record as JSON

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.

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')

The first 2 each produce:

'Note' object is not iterable

And the 3rd one gave me:

<Note: Note object> is not JSON serializable

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.

Thanks.

like image 406
mhost Avatar asked Jun 29 '26 04:06

mhost


2 Answers

From the docs:

The arguments to the serialize function are the format to serialize the data to (see Serialization formats) and a QuerySet to serialize.

Use filter() instead of get().

like image 116
Ignacio Vazquez-Abrams Avatar answered Jun 30 '26 18:06

Ignacio Vazquez-Abrams


Use:

serializers.serialize("json", [new_note])

(attention to square brackets around query object)

like image 45
Özgür Odabaşı Avatar answered Jun 30 '26 18:06

Özgür Odabaşı



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!