Many operations

Scenes:

On the table and book table (foreign key author_id)

By doing serialization of the book display, display of books in the corresponding vue, pay attention to display the author's name, rather than 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>

Published 84 original articles · won praise 1 · views 2099

Guess you like

Origin blog.csdn.net/lxp_mocheng/article/details/103549760