Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QuerySet is not JSON Serializable Django

newbie programming here. I have a model with many rows and I would like to pass each row to javascript.

First attempt:

Views.py

events = Events.objects.filter(user_id=user_id) // filter by user_id
context = {
            "email": request.user.email,
            "login": True,
            "objects": events,
        }
return render(request, 'fullcalendar/index.html', context)

Events is the name of the table and I stored each row in events. Passed that into a dict called context which is then passed to my template. Then from my template I was able to do something like this:

{% for object in objects %}
    <p>event.column_name</p>
{% endfor %}

and that would work fine, however I can't do that in the javascript section.

{% for object in objects %}
    var date = object.date // assuming object has a column named date
{% endfor %}

Second Attempt

So I did some research and decided to use json.

In Views.py I made the following change:

return render(request, 'fullcalendar/index.html', {"obj_as_json": simplejson.dumps(context)})

and from this I hoped to do this:

var objects = {{ obj_as_json }}

for object in objects 
    //Do some stuff

But I got the error QuerySet is not JSON Serializable Django. So I looked up how to serialize objects and made the following change:

data = serializers.serialize('json', events.objects.all())

But I got following error: 'QuerySet' object has no attribute 'objects'

Man, theres got to be a easier way to do what I want to do. Any ideas?

like image 939
anderish Avatar asked Feb 02 '17 01:02

anderish


1 Answers

Try this instead:

data = serializers.serialize('json', events)

The error message you got is telling you that events is already a QuerySet, there is no reason to try and do anything more with it.

You could also revisit your earlier attempt:

{% for object in objects %}
    var date = object.date // assuming object has a column named date
{% endfor %}

You need to actually use the Django object like this:

{% for object in objects %}
    var date = {{ object.date }}
{% endfor %}

The way you were doing it before object would simply be undefined and you would get the error cannot read property date of undefined

like image 135
Christopher Reid Avatar answered Sep 30 '22 23:09

Christopher Reid