models.py
class User(models.Model): name = models.CharField(verbose_name="Name", max_length=64)
serializer.py
class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name", ]
views.py
def get(self, request, *args, **kwargs): user_queryset = User.objects.all() user_data = UserSerializer(user_queryset, many=True).data return render(request, 'index.html', locals())
index.html
<body> {{ user_data|json_script:'user_data' }} <script type="text/javascript"> // 通过 js 获取 "user_data" 的数据, 并转换成 json 格式 user_data = JSON.parse(document.getElementById('user_data').textContent); </script> </body>
标签:script,py,queryset,json,user,data From: https://www.cnblogs.com/chaoqi/p/17365801.html