没有有DRF基础的小伙伴先去官网学习DRF基础
1,我们先在models.py定义类然后写两个字段
class JiLian(models.Model):
name = models.CharField(max_length=32)
pid = models.IntegerField(max_length=32, null=True) //pid用来写它对应的父级id
创建好之后 迁移数据库即可 先执行makemigrations 然后在执行 migrate
2,在views.py 写一个类视图
from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializers import *
def digui(pid, list):
data = []
for i in list:
if int(pid) == i['pid']:
# print(pid,i['pid'])
next_id = i['id']
i['chidren'] = digui(next_id, list)
data.append(i)
return data
class JlApiViews(ModelViewSet):
queryset = JiLian.objects.all()
serializer_class = JlSerrializers
def get_queryset(self): //因需要或取你想要的内容 在这里重写了get_queryset()
pid = 0
val = JiLian.objects.all().values()
a = digui(pid, val) //调用递归函数
return a
3,创建一个序列化器serializers.py
from rest_framework import serializers
from .models import *
class JlSerrializers(serializers.ModelSerializer):
//这是我们需要自定义字段 因为模板只定义了name 和pid 咱们递归的时新加了chidren
chidren = serializers.SerializerMethodField()
class Meta:
model = JiLian
fields = ['id', 'name', 'pid', 'chidren']
def get_chidren(self, queryset):
return queryset.get('chidren')
4,配置路由
from django.urls import path
from rest_framework.routers import SimpleRouter
from .views import JlApiViews
urlpatterns = []
router.register('jilian',JlApiViews,basename='jilian')
urlpatterns+=router.urls