DRF - 序列化之生成数据链接 hypermedialink
数据库结构和此文章相同:https://www.cnblogs.com/sch01ar/p/14295875.html
urls.py:
from django.urls import path, re_path from drf import views urlpatterns = [ path('userinfo/', views.UserInfoView.as_view()), re_path('group/(?P<group_pk>\d+)$', views.GroupView.as_view(), name='user_group'), ]
views.py:
from rest_framework.views import APIView from rest_framework import serializers from drf import models import json from django.shortcuts import HttpResponse class UserModelSerializers(serializers.ModelSerializer): # view_name 和 URL 的别名一致 # lookup_field="group_id" 是取 group 表下的 id 字段生成 URL 中的 pk 值 # lookup_url_kwarg 为 URL 中的参数即 pk 的值 group = serializers.HyperlinkedIdentityField(view_name="user_group", lookup_field="group_id", lookup_url_kwarg="group_pk") class Meta: model = models.UserInfo # 显示指定字段 fields = ["id", "username", "password", "group"] # 指定层次为 0 depth = 0 class UserInfoView(APIView): def get(self, request, *args, **kwargs): users = models.UserInfo.objects.all() # context={'request': request} 是生成链接要加的参数 ser = UserModelSerializers(instance=users, many=True, context={'request': request}) ret = json.dumps(ser.data, ensure_ascii=False) return HttpResponse(ret) class GroupSerializer(serializers.ModelSerializer): class Meta: model = models.UserGroup fields = "__all__" class GroupView(APIView): def get(self, request, *args, **kwargs): # 获取 URL 中的 group_pk 参数的值 pk = kwargs.get("group_pk") group_obj = models.UserGroup.objects.filter(pk=pk).first() ser = GroupSerializer(instance=group_obj, many=False) ret = json.dumps(ser.data, ensure_ascii=False) return HttpResponse(ret)
访问:/userinfo/
访问 /group/1