问题一:
class NewsSerializer(serializers.ModelSerializer):
# class Meta:
model = News
fields = '__all__'
class ShowNews(APIView):
def get(self,request):
news = News.objects.all()
ser = NewsSerializer(news,many=True)
return Response(ser.data)
序列化展示的时候在这里没有写 class Meta:,所以会报一个错
问题二:
一对多关系中,序列化如果不继承,在展示的时候会没有效果,具体代码如下:
<template>
<div>
<table border="1">
<tr>
<th>标题</th>
<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> # 展示外键在展示图书的时候展示作者姓名 而不是作者id
<td><button @click="zhuan(item.id)">转移</button></td>
</tr>
</table>
<div>
<button v-show="lastpage" @click="mychange(lastpage)">上一页</button>
<button v-for="index in all" @click="mychange(index)">{{ index }}</button>
<button v-show="nextpage" @click="mychange(nextpage)">下一页</button>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
datalist:[],
total:0,
cur:1,
lastpage:0,
nextpage:0,
all:0
}
},
mounted() {
this.mychange(1);
axios({
url:'http://localhost:8000/showbook/',
method:'get',
}).then(res=>{
this.datalist = res.data.data;
})
},
methods:{
zhuan(id){
this.$router.push({path:'/zhuan',query:{id:localStorage.getItem('userid'),bid:id}})
},
mychange(page){
axios({
url:'http://localhost:8000/showbook/',
method:'get',
params:{page:page,size:1}
}).then(res=>{
this.datalist = res.data.data;
if (page == 1){
this.lastpage = 0;
} else{
this.lastpage = page - 1
}
this.all = Math.ceil(res.data.total / this.cur);
if (page == this.all){
this.nextpage = 0
} else{
this.nextpage = page + 1;
}
})
}
}
}
</script>
class BookSerializer(serializers.ModelSerializer):
# author_id = UserSerializer()
class Meta:
model = Book
fields = '__all__'
问题三:
使用反序列化添加时,必须使用post添加,如果使用get添加,会加不进去的