Django DRF model 多对多关系使用示例

本例环境:Django=2.0.6 djangorestframework=3.9.2

1、模型示例

from django.db import models

class BaseModel(models.Model):
    sort = models.IntegerField(null=True, blank=True, verbose_name='排序')
    content = models.TextField(null=True, blank=True, verbose_name='描述')
    sort_time = models.DateTimeField(auto_now_add=True, verbose_name='排序时间')
    created = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        abstract = True


class FlowGroup(BaseModel):
    name = models.CharField(max_length=255, verbose_name='审批组名称')

    class Meta:
        db_table = 'A_FlowGroup_Table'
        verbose_name = '审批组表'
        verbose_name_plural = verbose_name


class FlowUser(BaseModel):
    name = models.CharField(max_length=255, verbose_name='审批组内员工名称-test')
    flow_group = models.ManyToManyField(FlowGroup, verbose_name='所属审批组', blank=True, related_name='flow_users')

    class Meta:
        db_table = 'A_FlowUser_Table'
        verbose_name = '审批组子表'
        verbose_name_plural = verbose_name

2、序列化器示例


from rest_framework import serializers
from rest_framework.serializers import SerializerMethodField
from rest_framework.validators import UniqueValidator
from rest_framework.utils import model_meta
import threading
from .models import *
import time
import datetime
                

class FlowGroupUseFlowUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = FlowUser
        exclude = ('deleted','flow_group',)


# 新增 审批组表 序列化器
class AddFlowGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = FlowGroup
        exclude = ('deleted',) # or fields = '__all__' or fields = ['field01','field01',]
        # read_only_fields = ('field01', )
# 修改 审批组表 序列化器
class UpdateFlowGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = FlowGroup
        exclude = ('deleted',) # or fields = '__all__' or fields = ['field01','field01',]
        # read_only_fields = ('field01', )
# 返回 审批组表 序列化器
class ReturnFlowGroupSerializer(serializers.ModelSerializer):
    flow_users = FlowGroupUseFlowUserSerializer(many=True, read_only=True)
    class Meta:

        model = FlowGroup
        exclude = ('deleted',) # or fields = '__all__' or fields = ['field01','field01',]
        # read_only_fields = ('field01', )
                


# 新增 审批组子表 序列化器
class AddFlowUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = FlowUser
        exclude = ('deleted',) # or fields = '__all__' or fields = ['field01','field01',]
        # read_only_fields = ('field01', )
# 修改 审批组子表 序列化器
class UpdateFlowUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = FlowUser
        exclude = ('deleted',) # or fields = '__all__' or fields = ['field01','field01',]
        # read_only_fields = ('field01', )
# 返回 审批组子表 序列化器
class ReturnFlowUserSerializer(serializers.ModelSerializer):
    flow_group = AddFlowGroupSerializer(many=True, read_only=True) # 以对象的方式返回 父级审批组
    class Meta:
        model = FlowUser
        exclude = ('deleted',) # or fields = '__all__' or fields = ['field01','field01',]
        # read_only_fields = ('field01', )
                
# 测试多对多查询使用的验证器
class TestManyToManySerializer(serializers.Serializer):
    flowuser = serializers.IntegerField()
    flowgroup = serializers.IntegerField()

3、视图函数示例

import uuid
import os
import requests
import json
import re
import time
import datetime
import random
import hashlib
import xml
import threading
from django.db.models import F, Q
from rest_framework import serializers, status, generics, mixins, viewsets
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.response import Response
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
# 官方JWT
# from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler ,jwt_response_payload_handler
# from rest_framework_jwt.authentication import JSONWebTokenAuthentication
# 缓存配置
from django.core.cache import cache
# 自定义的JWT配置 公共插件
from utils.utils import jwt_decode_handler,jwt_encode_handler,jwt_payload_handler,jwt_payload_handler,jwt_response_payload_handler,google_otp,VisitThrottle,getDistance,NormalObj
from utils.jwtAuth import JWTAuthentication
from utils.pagination import Pagination
from utils.permissions import JWTAuthPermission, AllowAllPermission, BaseAuthPermission
from .models import *
from .serializers import *
# from .filters import *
from functools import reduce
from urllib.parse import unquote_plus


# 审批组表 ModelViewSet视图
class FlowGroupViewset(ModelViewSet):
    '''
    修改局部数据
    create:  创建审批组表
    retrieve:  检索某个审批组表
    update:  更新审批组表
    destroy:  删除审批组表
    list:  获取审批组表列表
    '''
    queryset = FlowGroup.objects.all().order_by('-updated')
    authentication_classes = (JWTAuthentication,)
    permission_classes = [BaseAuthPermission, ]
    throttle_classes = [VisitThrottle]
    serializer_class = ReturnFlowGroupSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    ordering_fields = ('updated', 'sort_time', 'created',)
    pagination_class = Pagination

    def get_serializer_class(self):
        if self.action == 'create':
            return AddFlowGroupSerializer
        if self.action == 'update' or self.action == 'partial_update':
            return UpdateFlowGroupSerializer
        return ReturnFlowGroupSerializer

    def get_queryset(self):
        if bool(self.request.auth) and self.request.user.group_id == 1:
            return FlowGroup.objects.all().order_by('-updated')
        else:
            return FlowGroup.objects.filter(user_id=self.request.user.id).order_by('-updated')
                


# 审批组子表 ModelViewSet视图
class FlowUserViewset(ModelViewSet):
    '''
    修改局部数据
    create:  创建审批组子表
    retrieve:  检索某个审批组子表
    update:  更新审批组子表
    destroy:  删除审批组子表
    list:  获取审批组子表列表
    '''
    queryset = FlowUser.objects.all().order_by('-updated')
    authentication_classes = (JWTAuthentication,)
    permission_classes = [BaseAuthPermission, ]
    throttle_classes = [VisitThrottle]
    serializer_class = ReturnFlowUserSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    ordering_fields = ('updated', 'sort_time', 'created',)
    pagination_class = Pagination

    def get_serializer_class(self):
        if self.action == 'create':
            return AddFlowUserSerializer
        if self.action == 'update' or self.action == 'partial_update':
            return UpdateFlowUserSerializer
        return ReturnFlowUserSerializer

    def get_queryset(self):
        if bool(self.request.auth) and self.request.user.group_id == 1:
            return FlowUser.objects.all().order_by('-updated')
        else:
            return FlowUser.objects.filter(user_id=self.request.user.id).order_by('-updated')



class TestManyToManyView(generics.GenericAPIView):
    serializer_class = TestManyToManySerializer
    def post(self, request):
        '''
        测试ManyToMany接口
        '''
        try:
            json_data = {"message": "ok", "errorCode": 0, "data": {}}
            serializer = self.get_serializer(data=request.data)
            if not serializer.is_valid():
                return Response({"message": str(serializer.errors), "errorCode": 4, "data": {}})
            flowuser = serializer.data.get('flowuser')
            flowgroup = serializer.data.get('flowgroup')
            flowuser_obj = FlowUser.objects.filter(id=flowuser).first()
            flowgroup_obj = FlowGroup.objects.filter(id=flowgroup).first()
            print(flowuser_obj)
            if flowuser_obj:
                print('正向查找:通过fowuser找到所有flowgroup:')
                print(flowuser_obj.flow_group.all())
            if flowgroup_obj:
                print('正向查找:通过flowgroup找到所有fowuser:')
                print(flowgroup_obj.flow_users.all())
            return Response(json_data)
        except Exception as e:
            print('发生错误:',e)
            return Response({"message": "出现了无法预料的view视图错误:%s" % e, "errorCode": 1, "data": {}})

4、路由示例

添加在项目和settings.py同级的urls.py中

from your_app.views import FlowGroupViewset, FlowUserViewset, TestManyToManyView, FlowGroupSearchView
# 审批组表管理
router.register(r'flowgroup', FlowGroupViewset, base_name='审批组表管理')
# 审批组子表管理
router.register(r'flowuser', FlowUserViewset, base_name='审批组子表管理')

你可能感兴趣的:(django,Python,Django)