Dd Xia
Dd Xia

Reputation: 55

Is there any way convert Django model queryset to json or json string in template?

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

Upvotes: 2

Views: 7329

Answers (2)

Yannic Hamann
Yannic Hamann

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

Matt Hardcastle
Matt Hardcastle

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

Related Questions