captDaylight
captDaylight

Reputation: 2234

Passing JSON with Django

I'm passing information to a Processing sketch from a Django backend. The problem arises with "lectures", it seems that it is not serializable. I'm missing something very basic methinks.

def get(request, last_update = None):
    timestamp = time.time() 
    if last_update:
        last_update = datetime.fromtimestamp(float(last_update))
        lectures = Lecture.objects.all().filter(datetime_edit__gt=last_update)
    else:
        lectures = Lecture.objects.all()
    updates = {'timestamp': timestamp, 'lectures': lectures}
    print updates
    return HttpResponse(json.dumps(updates), mimetype="application/json")

Here is the response that I'm getting in the browser.

[<Lecture: whales>, <Lecture: cats>, <Lecture: rain>, <Lecture: china>] is not JSON serializable

Upvotes: 1

Views: 255

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799380

QuerySet cannot be serialized in this manner. Use .values() and list() to turn it into a basic Python structure (i.e. a list of dicts) first.

Upvotes: 3

mikerobi
mikerobi

Reputation: 20878

The JSON serialize does not support serialization of arbitrary class instances. You should convert Lecture records into dictionaries before serializing.

Upvotes: 2

Related Questions