django的多对多表
今天就以小说表来演示一下
首先我们要创建一个django项目
django-admin squashmigrations 项目名
django-admin startapp 我们的app名
注意创建app时我们要进入到我们的项目文件里
然后开始配置我们的django配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'goods',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL=True
接着来书写我们的model类
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length=20)
password = models.CharField(max_length=20)
class types(models.Model):
types = models.CharField(max_length=20)
class xs(models.Model):
title = models.CharField(max_length=20)
num = models.IntegerField()
count = models.IntegerField()
types_d = models.ForeignKey(to=types,on_delete=models.CASCADE)
class pJ(models.Model):
countext = models.CharField(max_length=20)
data = models.DateTimeField(auto_now_add=True)
username = models.ForeignKey(to=User,on_delete=models.CASCADE)
xs_d = models.ForeignKey(to=xs,on_delete=models.CASCADE)
model类写完之后我们不要忘记对model类进行迁移
python manage.py makemigrations
python manage.py migrate
紧接着是序列化器(序列化器需要自己创建python文件)
from rest_framework.serializers import ModelSerializer
from goods.models import *
from rest_framework import serializers
class UserModelSerializer(ModelSerializer):
class Meta:
model = User
fields = '__all__'
class typesModelSerializer(ModelSerializer):
class Meta:
model = types
fields = '__all__'
class xsModelSerializer(serializers.ModelSerializer):
typess = serializers.SerializerMethodField()
def get_typess(self, obj):
return obj.types_d.types
class Meta:
model = xs
fields = '__all__'
class pJModelSerializer(ModelSerializer):
class Meta:
model = pJ
fields = '__all__'
然后开始书写我们的视图
from django.shortcuts import render
# Create your views here.
from rest_framework.generics import ListCreateAPIView
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.myser import *
class userAPIView(ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserModelSerializer
class user2APIView(RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserModelSerializer
class typesAPIView(ListCreateAPIView):
queryset = types.objects.all()
serializer_class = typesModelSerializer
class types2APIView(RetrieveUpdateDestroyAPIView):
queryset = types.objects.all()
serializer_class = typesModelSerializer
class xsAPIView(ListCreateAPIView):
queryset = xs.objects.all()
serializer_class = xsModelSerializer
class xs2APIView(APIView):
def get(self,request,id):
print(id)
obj = xs.objects.get(id=id)
print(obj)
obj.num += 1
obj.save()
ser = xsModelSerializer(obj)
return Response(ser.data, status=200)
def put(self,request,id):
print(id)
types_id = request.data.get("id")
xs.objects.filter(id=id).update(types_d_id=types_id)
return Response({"msg","成功"})
class pjAPIView(ListCreateAPIView):
serializer_class = pJModelSerializer
def get_queryset(self):
id = self.request.GET.get('id')
print(id)
return pJ.objects.filter(xs_d_id=id)
class pj2APIView(RetrieveUpdateDestroyAPIView):
queryset = pJ.objects.all()
serializer_class = pJModelSerializer
然后开始配置我们的主路由
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('goods.urls'))
]
然后是子路由(子路由需要手动创建python文件注意要创建在app中)
from django.urls import path
from goods.views import *
urlpatterns = [
path('user/',userAPIView.as_view()),
path('types/',typesAPIView.as_view()),
path('xs/',xsAPIView.as_view()),
path('pj/',pjAPIView.as_view()),
path('user2/<pk>/', user2APIView.as_view()),
path('types2/<pk>/', types2APIView.as_view()),
path('xs2/<id>/', xs2APIView.as_view()),
path('pj2/<pk>/', pj2APIView.as_view())
]
我们的django后端就写完了现在开始写前端
我们的第一个页面用户的添加
<template>
<div>
<h1>用户添加</h1>
用户名: <input type="text" v-model="name">
密码: <input type="text" v-model="password">
<button @click="btn">添加</button></div>
</template>
<script>
export default {
name: "w1",
data(){
return{
data:'',
password:''
}
},
methods:{
btn(){
this.$axios.post('user/',{
name:this.name,
password:this.password
})
.then(res=>{
console.log(res.data)
this.$router.push('/w2')
})
}
}
}
</script>
<style scoped>
</style>
然后是我们的分类添加
<template>
<div>
<h1>添加分类</h1>
分类: <input type="text" v-model="types">
<button @click="btn">添加</button>
</div>
</template>
<script>
export default {
name: "w2",
data(){
return{
types:''
}
},
methods:{
btn(){
this.$axios.post('types/',{
types:this.types
})
.then(res=>{
console.log(res.data)
this.$router.push('/w3')
})
}
}
}
</script>
<style scoped>
</style>
然后是添加小说
<template>
<div>
<h1>添加小说</h1>
名称: <input type="text" v-model="title">
浏览量: <input type="text" v-model="num">
评论量: <input type="text" v-model="count">
分类: <select name="" id="" v-model="types_d">
<option :value="i.id" v-for="i in data">
{{ i.types }}
</option>
</select>
<button @click="btn">添加</button>
</div>
</template>
<script>
export default {
name: "w3",
data() {
return {
title: '',
num: '',
count: '',
types_d: '',
data: ''
}
},
methods: {
btn() {
this.$axios.post('xs/', {
title: this.title,
num: this.num,
count: this.count,
types_d: this.types_d
})
.then(res => {
console.log(res.data)
this.$router.push('/w4')
})
},
ten() {
this.$axios.get('types/')
.then(res => {
console.log(res.data)
this.data = res.data
})
},ten1() {
this.$axios.get('user/')
.then(res => {
console.log(res.data)
this.data = res.data
})
}
},
mounted() {
this.ten()
this.ten()
this.ten1()
}
}
</script>
<style scoped>
</style>
然后是我们小说的展示
<template>
<div>
<table border="2">
<tr>
<td>小说名</td>
<td>浏览量</td>
<td>评价量</td>
<td>分类</td>
<td>详情</td>
<td>转移</td>
</tr>
<tr v-for="i in data">
<td>{{i.title}}</td>
<td>{{i.num}}</td>
<td>{{i.count}}</td>
<td >{{i.typess}}</td>
<td><button @click="btn2(i.id)">详情</button></td>
<td><button @click="btn3(i.id)">转移</button></td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "w4",
data(){
return{
data:'',
datas:''
}
},
methods:{
ten(){
this.$axios.post('pj/',{
countext:this.countext
})
.then(res=>{
console.log(res.data)
})
},
btn(){
this.$axios.get('xs/')
.then(res=>{
console.log(res.data)
this.data = res.data
})
},
btn1(){
this.$axios.get('types/')
.then(res=>{
console.log(res.data)
this.datas = res.data
})
},
btn2(id){
this.$router.push({
name:'w5',
query:{
id:id
}
})
},
btn3(id){
this.$router.push({
name: 'w6',
query: {
id: id
}
})
}
},
mounted() {
this.btn()
this.btn1()
}
}
</script>
<style scoped>
</style>
紧接着就是我们的详情页面
<template>
<div>
<h1>详情</h1>
{{data.typess}}=={{data.title}}=={{data.num}}=={{data.count}}
<h6 v-for="i in datas">{{i.countext}}</h6>
评论: <input type="text" v-model="countext">
用户:<select v-model="username">
<option :value="i.id" v-for="i in pdd">
{{i.name}}
</option>
</select>
小说:<select v-model="xs_d">
<option :value="i.id" v-for="i in xdd">
{{i.title}}
</option>
</select>
<button @click="btn2">添加</button>
</div>
</template>
<script>
export default {
name: "w5",
data(){
return{
id:this.$route.query.id,
data:'',
datas:'',
pdd:'',
xdd:'',
countext:'',
username:'',
xs_d:''
}
},
methods:{
btn(){
this.$axios.get('xs2/'+ this.id +'/')
.then(res=>{
console.log(res.data)
this.data = res.data
})
},
btn1(){
this.$axios.get('pj/?id=' + this.id)
.then(res=>{
console.log(res.data)
this.datas = res.data
})
},
btn2(){
this.$axios.post('pj/',{
countext:this.countext,
username:this.username,
xs_d:this.xs_d
})
.then(res=>{
console.log(res.data)
this.btn1()
})
},
ten(){
this.$axios.get('user/')
.then(res=>{
console.log(res.data)
this.pdd = res.data
})
},
ten1(){
this.$axios.get('xs/')
.then(res=>{
console.log(res.data)
this.xdd = res.data
})
}
},
mounted() {
this.btn()
this.btn1()
this.ten()
this.ten1()
}
}
</script>
<style scoped>
</style>
转移页面
<template>
<div>
<h1>转移</h1>
<select name="" id="" v-model="types_d">
<option :value="i.id" v-for="i in data">
{{i.typess}}
</option>
</select>
<button @click="btn1">转换</button>
</div>
</template>
<script>
export default {
name: "w6",
data(){
return{
data:"",
types_d:"",
id:this.$route.query.id
}
},
methods:{
btn(){
this.$axios.get('xs/')
.then(res=>{
console.log(res.data)
this.data=res.data
})
},
btn1(){
this.$axios.put('xs2/'+this.id+'/',{
id:this.id
})
.then(res=>{
console.log(res.data)
this.$router.push({
name:'w4'
})
})
}
},
mounted() {
this.btn()
}
}
</script>
<style scoped>
</style>