Reputation: 55
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.
Upvotes: 2
Views: 7329
Reputation: 5205
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 %}
Upvotes: 5
Reputation: 678
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.
Upvotes: 2