django多对多展示

本文介绍了在Django中如何处理多对多关系,包括从老师角度查询学生和从学生角度查询老师的方法。通过使用反向查找和外键,可以有效地匹配并序列化展示相关数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过老师查学生:

先获取老师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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值