多对多查询

  • 模型

    from django.db import models
    
    # 学生类
    class Student(models.Model):
        name = models.CharField(max_length=32)
    # 老师类
    class Teacher(models.Model):
        name = models.CharField(max_length=32)
        students = models.ManyToManyField(to='Student',related_name='stu')
    
  • 视图

    • 查询老师有多少名学生

      from rest_framework.views import APIView
      from rest_framework.response import Response
      from . import models
      # 老师类
      class TeacherView(APIView):
          def get(self, request):
              teacherobj = models.Teacher.objects.filter(id=3).first()
                      stuobj = teacherobj.students.all()
              stu_data = [{"id":i.id,"name":i.name} for i in stuobj]
              return Response({
                  "status": 200,
                    "data":{
                        "id":teacherobj.id,
                        "name":teacherobj.name,
                        "stu":stu_data
                  }
              })
      
    • 查询学生有多名老师

      from rest_framework.views import APIView
      from rest_framework.response import Response
      from . import models
      # 学生类
      class StudentView(APIView):
          def get(self, request):
              studentobj = models.Student.objects.filter(id=3).first()
                      teacherobj = studentobj.stu.all()
              teacher_data = [{"id":i.id,"name":i.name} for i in teacherobj]
              return Response({
                  "status": 200,
                    "data":{
                        "id":studentobj.id,
                        "name":studentobj.name,
                        "teacher":teacher_data
                  }
              })
      

results matching ""

    No results matching ""