一对多表的添加
前端
路由
import Vue from 'vue' import Router from 'vue-router' import addbook from '@/components/AddBook' Vue.use(Router) export default new Router({ routes: [ { path: '/addbook', name: 'addbook', component: addbook } ] })
代码
<template> <div id='addbook'> <p> 名称 <input type="text" v-model="name"></p> <p> 价格 <input type="text" v-model="price"></p> <p> 分类 <select v-model="cate_id"> <option v-for='i in cates' :value="i.id"></option> </select> </p> <button @click="sub">添加图书</button> </div> </template> <script> export default { name:'addbook', data() { return { name:'', price:0, cate_id:0, value:"", cates:[] } }, mounted(){ this.axios({ url:'/api/app03/cate/', method:'get' }).then(res=>{ this.cates = res.data.data; }) }, methods:{ sub:function(){ let data = { "name":this.name, "price":this.price, "cate_id":this.cate_id } //發送數據 this.axios({ url:'/api/app03/book/', method:'post', data:data }).then(res=>{ if(res.data.status==200){ // 添加图书成功,跳转到图书列表页 }else{ alert(res.data.msg); } }) } } } </script>
后端
模型
from django.db import models # 图书分类表 class Category(models.Model): # 分类名称 name = models.CharField(max_length=32,unique=True) # 图书表 class Book(models.Model): # 图书名称 name = models.CharField(max_length=32,unique=True) # 图书价格 price = models.DecimalField(max_digits=9,decimal_places=2) # 图书添加时间 addtime = models.DateTimeField(auto_now_add=True) # 外键 cate = models.ForeignKey('Category',on_delete=models.CASCADE)
路由
urlpatterns = [ path('book/',views.BookView.as_view()), ]
视图
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 图书 class BookView(APIView): def post(self,request): data = request.data flag = models.Book.objects.create(**data) # 判断入库情况 if flag: return Response({ "status":200, "msg":"添加数据成功" }) return Response({ "status": 201, "msg": "添加数据失败" }) # 分类 class CateView(APIView): def get(self,request): books = models.Category.objects.all() data = [{"id":i.id,"name":i.name} for i in books] return Response({ "status":200, "msg":"", "data":data })