一对多操作

场景:

作者表和图书表(外键author_id)

通过序列化对图书做展示,在vue中展示图书所对应的作者,注意展示作者名字,而不是id

class UserSer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class BookSer(serializers.ModelSerializer):
    author_id = UserSer()  # 在这里需要继承
    # 这里的author_id 必须和图书表中的外键名字一样
    class Meta:
        model = Book
        fields = '__all__'


class ShowBook(APIView):
    def get(self,request):
        book = Book.objects.all()
        ser = BookSer(book,many=True)
        return Response({
            'code':200,
            'data':ser.data
        })
<template>
    <div>
      <table border="1">
        <tr>
          <th>标题</th>
          <th>价格</th>
          <th>作者</th>
        </tr>
        <tr v-for="item in datalist">
          <td>{{ item.title }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.author_id.username }}</td>
        </tr>
      </table>
    </div>
</template>

<script>
  import axios from 'axios'
    export default {
        data(){
          return{
              datalist:[]
          }
        },
      mounted() {
         axios({
              url:'http://127.0.0.1:8000/showbook/',
              method:'get',
            }).then(res=>{
              console.log(res);
              this.datalist = res.data.data;
            })
      }
    }
</script>

<style scoped>

</style>

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

猜你喜欢

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