I want to combine react (or vue) with django template, but I don't want to change the backend to restful api. So I wonder is there any way convert Django model queryset to json or json string in template, so that I can fetch the data from dom used in jsx or vue.
Asked
Active
Viewed 7,132 times
2 Answers
5
To serialize a Django
queryset with core functionality take a look here:
from django.core.serializers import serialize
from models import MyModel
serialize('json', MyModel.objects.all())
In order to access the JSON
in your template, without using a REST API
resource or AJAX
, take advantage of custom template tags/filters.
tags.py
:
from django.template import Library
register = Library()
@register.filter
def json(queryset):
return serialize('json', queryset)
HTML Template:
{% load tags %}
{% users|json %}

Yannic Hamann
- 4,655
- 32
- 50
2
You could use just the serialization component of Django Rest Framework. It provides a declarative serializer that is more flexible than the one in Django.
An added benefit, if/when you want to provide a full restful API you'll already have a good hunk of the code for it written.

Matt Hardcastle
- 638
- 3
- 9