django多对多展示

通过老师查学生:

先获取老师id,然后查学生表(反向查找) teacher__id ,匹配传过来的老师id,最后序列化展示

通过学生查老师:

先获取学生id,然后查老师表(外键)stu,匹配传过来的学生id,最后序列化展示

class ShowTea(APIView):    # 首次展示老师 
    def get(self,request):
        tea = Teacher.objects.all()
        ser = TeaSer(tea, many=True)
        return Response({
            'code': 200,
            'data': ser.data
        })

class Shows(APIView):        # 点击老师展示他的学生
    def post(self,request):
        id = request.data.get('id')  # 前端传过来的老师的id
        stu = Student.objects.filter(teacher__id=id)  # 学生表中隐藏的teacher字段加双下划綫id等于老师的id
        ser = StudentSer(stu,many=True)
        return Response(ser.data)

class Showtt(APIView):      # 点击学生展示他的老师
    def post(self,request):
        id = request.data.get('id')  # 前端传过来的学生的id
        tea = Teacher.objects.filter(stu=id)  # 老师表外键学生id等于前端学生id
        tea = TeacherSer(stu,many=True)
        return Response(ser.data)
<template>
    <div>
      <table border="1">
        <tr>
          <th>老师</th>
        </tr>
        <tr v-for="item in datalist">
          <td><button @click="shos(item.id)">{{ item.name }}</button></td>  # 展示老师名字,点击时触发shos方法,将展示效果实现在div标签
        </tr>
        <div v-for="i in ss">   # 该标签展示的是老师对应的学生
          <button @click="ttt(i.id)">{{ i.name }}</button> # 点击触发ttt方法,将展示效果实现在li标签
        </div>
        <li v-for="i in tt">{{ i.name }}</li> # 该标签展示的是学生对应的老师
      </table>
    </div>
</template>

<script>
  import axios from 'axios'
    export default {
        data(){
          return{
            datalist:[],
            ss:[],
            tt:[]
          }
        },
      mounted() {
           axios({
            url:'http://localhost:8000/showtea/',
            method:'get'
          }).then(res=>{
            console.log(res);
            this.datalist = res.data.data;
          })
      },
      methods:{
          shos(id){
             axios({
                url:'http://localhost:8000/shows/',
                method:'post',
                data:{'id':id}
              }).then(res=>{
                console.log(res);
                this.ss = res.data
              })
          },
        ttt(id){
             axios({
                url:'http://localhost:8000/showtt/',
                method:'post',
                data:{'id':id}
              }).then(res=>{
                console.log(res);
                this.tt = res.data
              })
        }
      }
    }
</script>

<style scoped>

</style>

发布了84 篇原创文章 · 获赞 1 · 访问量 2101

猜你喜欢

转载自blog.csdn.net/lxp_mocheng/article/details/103463324