我正在使用Django和Django Rest Framework构建REST API。它是教师可以创建课堂的应用程序。课堂上有讲座和其他材料。这些教室只能由业主或管理员访问。为了控制对不同端点的访问,我正在使用Django-Role-Permissions。
每当我尝试使用Django Rest Framework和Django-Role-Permission的BasePermission检查权限时,我收到的数据库查询数量过多。例如,当我点击List-Create Classroom端点时,我得到40个查询,这非常奇怪。
这是我的课堂模式
from django.db import models
class Classroom(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=100, null=False, blank=False)
description = models.CharField(max_length=200, null=False, blank=False)
course = models.ForeignKey(Course, null=True, blank=True, on_delete=models.SET_NULL)
semester = models.ForeignKey(Semester, null=True, blank=True, on_delete=models.SET_NULL)
teacher = models.ForeignKey(User, related_name='classrooms', on_delete=models.CASCADE)
archive = models.BooleanField(default=0)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
这是我的ListCreateClassroomAPIView
from rest_framework.generics import ListCreateAPIView
class ListCreateClassroomAPIView(ListCreateAPIView):
serializer_class = ClassroomSerializer
permission_classes = (IsAuthenticated, IsAuthorizedToCreate)
def get_queryset(self):
if has_permission(self.request.user, 'view_classroom'):
return Classroom.objects.all().select_related('teacher').select_related('teacher__employee_details')
return Classroom.objects.filter(teacher=self.request.user).select_related('teacher'). \
select_related('teacher__employee_details')
def perform_create(self, serializer):
course = Course.objects.get(id=self.request.data.get('course'))
semester = Semester.objects.get(id=self.request.data.get('semester'))
serializer.save(teacher=self.request.user, course=course, semester=semester)
如果用户有' view_classroom'那么我试图返回所有教室。允许或返回用户拥有的教室。
权限类:
from rest_framework.permissions import BasePermission, SAFE_METHODS
from rolepermissions.checkers import has_permission
class IsAuthorizedToCreate(BasePermission):
def has_permission(self, request, view):
if request.method in SAFE_METHODS:
return True
return has_permission(request.user, 'create_classroom')
来自Django调试工具栏的SQL Traceback SQL Queries from Django Debug Toolbar
谁能告诉我我做错了什么?