前几篇博客讲了一下drf的一些基本知识,不懂drf的小伙伴可以进去学习DRF学习笔记(准备)(已经会的忽略这句),接下来就举个简单的栗子说明页面如何drf传输的数据。
先创建一个django项目,并添加一个app,我添加的app是demo(别忘了在settings中引用创建的app)。之后添加如下代码(下面是本人的模型类,你也可以根据自己的模型类对代码进行修改):
demo/models.py
from django.db import models
# Create your models here.
class ClassInfo(models.Model):
number = models.IntegerField(verbose_name='班级编号')
grade = models.CharField(verbose_name='年级', max_length=3, choices=(('一年级', '一年级'), ('二年级', '二年级'), ('三年级', '三年级')))
demo/serializers.py
from rest_framework import serializers
from demo.models import ClassInfo
class ClassInfoSerializer(serializers.ModelSerializer):
"""班级数据序列化器"""
class Meta:
model = ClassInfo
fields = '__all__'
demo/views.py
from demo.models import ClassInfo
from demo.serializers import ClassInfoSerializer
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
class ClassInfoViewSet(mixins.ListModelMixin, GenericViewSet):
queryset = ClassInfo.objects.all()
serializer_class = ClassInfoSerializer
demo/urls.py
from django.urls import path
from demo import views
urlpatterns = [
path('classes_set/', views.ClassInfoViewSet.as_view({'get': 'list'})),
]
项目的根urls.py
urlpatterns = [
path('demo/', include('demo.urls')),
]
在templates目录下添加html:
templates/drf_test.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drf_testtitle>
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js" charset="utf-8">script>
head>
<body>
<table border="1" id="class_data">
<tr>
<th>班级编号th>
<th>年级th>
tr>
table>
body>
<script>
var get_url = 'http://127.0.0.1:8000/demo/classes_set/'
$.ajax(
{
type: 'get',
url: get_url,
dataType: 'json',
success: function (data) {
for(i = 0; i < data.length; i++){
$("#class_data").append('' + data[i].number + ' ' + '' + data[i].grade + ' ')
}
}
}
)
script>
html>
添加视图:
demo/views.py
def drf_test(request):
return render(request, 'drf_test.html')
添加url:
demo/urls.py
urlpatterns = [
path('drf_test/', views.drf_test), # 添加了这一行
]