QuerySet is not JSON Serializable Django

newbie programming here. I have a model with many lines, and I would like to pass each line to javascript.

First try:

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 saved each row in Events . Passed this to 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 this will work fine, however I cannot do this 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 was hoping to do this:

 var objects = {{ obj_as_json }} for object in objects //Do some stuff 

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

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

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

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

+5
source share
1 answer

Try this instead:

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

The error message you received tells you that events already a QuerySet, there is no reason to try and do something else with it.

You can also return to the previous attempt:

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

You need to use the Django object as follows:

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

The way you did this before object would be just undefined and you would get the error cannot read property date of undefined

+2
source

Source: https://habr.com/ru/post/1263708/


All Articles