I\'m trying to pass a Query Set from Django to a template with javascript.
I\'ve tried different approaches to solve this:
1. Normal Approach - Javas
Django querysets are serializable by JSON. Some field types (such as date, apparently), can't be serialized at is. A workaround for date objects is posted in another question on JSON and Python.
I would recommend creating dictionaries directly in the JavaScript itself. Given models like this:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
content = models.TextField()
class Author(models.Model):
article = models.ForeignKey("Article", related_name="authors")
first_name=models.CharField(max_length=100)
last_name=models.CharField(max_length=100)
I'd do something like this in the template:
If you maybe worded the question a little poorly and aren't planning on inserting code in a tag and actually need JSON for some reason, I'd simply do a loop in the view and create a list of dicts, which JSON has no problem serializing, and JavaScript no problem in understanding.