2

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.

enter image description here enter image description here

Dd Xia
  • 55
  • 2
  • 6
  • Possible duplicate of [Output Django queryset as JSON](https://stackoverflow.com/questions/15874233/output-django-queryset-as-json) – souldeux Nov 09 '17 at 14:24

2 Answers2

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