当前位置:网站首页>Realization of specification management and specification option management functions
Realization of specification management and specification option management functions
2022-07-27 08:29:00 【qishaoawei】
Back end
Create model classes
Specification model class and specification option model class
Specification model class foreign key binding spu surface
Specification option class binding specification table
# Specification model class definition
class SPUSpec(models.Model):
name=models.CharField(' Specification name ',max_length=20)
spu=models.ForeignKey(SPUS,on_delete=models.CASCADE,verbose_name=' Belongs to spu')
def __str__(self):
return self.name
class Meta:
db_table='spu_spec'
verbose_name_plural='spu Specifications '
# Specification option model class definition
class SpecOption(models.Model):
value=models.CharField(' Option value ',max_length=20)
spec=models.ForeignKey(SPUSpec,on_delete=models.CASCADE,verbose_name=' Specification name ')
def __str__(self):
return '%s:%s-%s'%(self.spec.spu.name,self.spec.name,self.value)
class Meta:
db_table='spec_option'
verbose_name_plural=' Specification option value '
Write a serializer
#SPU Serializer of specification model class
class SPUSpecSer(serializers.ModelSerializer):
spu_name=serializers.SerializerMethodField(read_only=True)
def get_spu_name(self,obj):
return obj.spu.name
class Meta:
model=SPUSpec
fields='__all__'
read_only_fields=['id']
#SPU Serializer of model class --- Concise Edition
class SPUSerSimple(serializers.ModelSerializer):
class Meta:
model=SPUS
fields=["id","name"]
read_only_fields=['id','name']
# Serializer of specification option value model class
class SpecOptionSer(serializers.ModelSerializer):
spec_name=serializers.SerializerMethodField(read_only=True)
def get_spec_name(self,obj):
return obj.spec.name
class Meta:
model=SpecOption
fields='__all__'
read_only_fields=['id']
Write view classes
# View of specifications
class SPUSpecView(ModelViewSet):
queryset = SPUSpec.objects.all()
serializer_class = SPUSpecSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
pagination_class = MyPagination
#spu Simplified view Avoid the pager causing incomplete data display
class SPUAllAPIView(ModelViewSet):
queryset = SPUS.objects.all()
serializer_class = SPUSerSimple
# View of specification option values
class SpecOptionViewSet(ModelViewSet):
queryset = SpecOption.objects.all()
serializer_class = SpecOptionSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
pagination_class = MyPagination
# Load all specifications spuSpec Avoid data incompleteness caused by the pager
class SPUSpecAllAPIView(ListAPIView):
queryset = SPUSpec.objects.all()
serializer_class = SPUSpecSer
Configure the routing
from django.urls import path
from rest_framework import routers
from .views import *
urlpatterns = [
# Load all specifications spuSpec Avoid data incompleteness caused by the pager
path('spuSpecs/all/',SPUSpecAllAPIView.as_view())
]
# Brand routing
router=routers.SimpleRouter()
router.register('spusall',SPUAllAPIView) #spu Simplified routing
router.register('spuSpecs',SPUSpecView,'spuSpecs') # Specification route
router.register('specOption',SpecOptionViewSet,'specOption') # Specification options routing
urlpatterns+=router.urls
front end
Find the corresponding veu Components , To configure
Realize the addition, deletion, modification and check of specifications
for example :Specs.vue Get all the data
<script> import BreadCrumb from '@/components/widget/BreadCrumb' // Add specifications import AddSpecs from '@/components/widget/AddSpecs' // Exhibition Delete modify specifications import SpecsTable from '@/components/widget/SpecsTable' // import cons from '@/components/constant' export default {
name: 'Specs', data () {
return {
page:1, total:0, pagesize:3, aSpecsList:[] } }, components:{
BreadCrumb, AddSpecs, SpecsTable }, mounted(){
this.fnGetData(1); }, methods:{
fnGetData(num){
this.axios.get('/v1/goods/spuSpecs/',{
params:{
page:num ? num :this.page, pageSize:this.pagesize }, headers:{
Authorization:'JWT '+localStorage.token }, responseType:'json' }).then((result) => {
console.log("111111111111111111",result) this.aSpecsList=result.data.results this.total=result.data.count }).catch((err) => {
console.log('err:',err) }); }, // Paging time function fnGetPage(num){
this.page=num this.fnGetData(num)a } } } </script>
for example :SpecsTable.vue Display and modify data
Modify the route in the event , Field etc.
<script> let token = localStorage.token; export default {
name: 'AuthorityTable', props:['specs'], data () {
var validateName = (rule, value, callback) => {
if (value === '') {
callback(new Error(' Specification name cannot be empty ')); } else {
callback() } }; return {
pop_show:false, edit_id:'', spus_list:[], specsForm:{
name:'', spu:'' }, rulesSpecsForm:{
name: [ {
validator:validateName, trigger: 'blur' } ] } } }, methods:{
// Click Edit trigger method fnPopShow(id){
this.pop_show = true; this.edit_id = id; this.axios.get('/v1/goods/spuSpecs/'+this.edit_id+'/', {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
this.specsForm.name = res.data.name; this.specsForm.spu = res.data.spu; }).catch(err=>{
console.log(' Get wrong information ',err); }); }, // Submit submitForm(){
this.axios.put('/v1/goods/spuSpecs/'+this.edit_id+'/', {
"name": this.specsForm.name, "spu": this.specsForm.spu, }, {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json' }).then(res=>{
this.$message({
type: 'success', message: ' The specification is modified successfully !' }); this.pop_show = false; this.$emit('fnResetTable'); this.resetForm('specsForm'); }).catch(err=>{
console.log(err.response); }) }, fnDelSpecs(id){
this.edit_id = id; this.$confirm(' This operation will delete the specification , Whether or not to continue ?', ' Tips ', {
confirmButtonText: ' determine ', cancelButtonText: ' Cancel ', type: 'warning' }).then(() => {
this.axios.delete('/v1/goods/spuSpecs/'+this.edit_id+'/',{
headers: {
'Authorization': 'JWT ' + token }, responseType:'json' }).then(res=>{
if (res.status==204){
this.$message({
type: 'success', message: ' Delete successful !' }); this.$emit('fnResetTable'); }else{
this.$message({
type:'error', message:' Delete failed ' }) } }).catch(err=>{
if(err.response.status==404){
this.$message({
type:'info', message:' Specification not found !' }); } }) }).catch(() => {
this.$message({
type: 'info', message: ' Delete cancelled ' }); }); }, // Get all spu data fnGetSPUs(){
this.axios.get('/v1/goods/spusall/', {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
this.spus_list = res.data; }).catch(err=>{
console.log(err.response); }); }, resetForm(formName){
this.$refs[formName].resetFields(); } }, mounted(){
this.fnGetSPUs(); } } </script>
for example :AddSpecs.vue Modify the data
Modify the route in the event , Field etc.
Add the field of binding foreign key to realize the drop-down box addition
Adding is similar to modifying acquired data
<script> let token = localStorage.token; export default {
name: 'AddUser', data () {
var validateName = (rule, value, callback) => {
if (value === '') {
callback(new Error(' Specification name cannot be empty ')); } else {
callback() } }; return {
pop_show:false, spus_list:[], specsForm:{
name:'', spu_id:'' }, rulesSpecsForm:{
name: [ {
validator:validateName, trigger: 'blur' } ] } } }, methods:{
submitForm(){
// console.log("spu_id<<<<<",this.specsForm.spu_id) this.axios.post('/v1/goods/spuSpecs/', {
"name":this.specsForm.name, "spu":this.specsForm.spu_id }, {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json' }) .then(res=>{
if(res.status==201){
this.$message({
type: 'success', message: ' Specification added successfully !' }); this.pop_show = false; this.$emit('fnResetTable'); this.resetForm('spcesForm'); } }).catch(err=>{
if(err.response){
var errmsg = err.response.data; if(errmsg.name){
this.$message({
type:'info', message:errmsg.name[0] }); } if(errmsg.non_field_errors){
this.$message({
type:'info', message:errmsg.non_field_errors[0] }); } } }); }, // Get all spu data fnGetGoods(){
this.axios.get('/v1/goods/spusall/', {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
this.spus_list = res.data; }).catch(err=>{
console.log(err.response); }); }, resetForm(formName){
this.$refs[formName].resetFields(); } }, mounted(){
this.fnGetGoods(); } } </script>
The specification options are similar to those above , Find the corresponding vue Component
边栏推荐
- All in one 1319 - queue for water
- "Basic knowledge of PHP" implement mathematical operations in PHP
- Vcenter7.0 managing esxi7.0 hosts
- QT creator code style plug-in beautifier
- Design and development of GUI programming for fixed-point one click query
- [MRCTF2020]PYWebsite 1
- Shenzhi Kalan Temple
- Help send some recruitment. If you are interested, you can have a look
- Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering
- STM32 small bug summary
猜你喜欢

On Valentine's day, I drew an object with characters!

Functions and arrow functions

Leetcode54. Spiral matrix

Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?

UVM Introduction Experiment 1

Hundreds of people participated. What are these people talking about in the opengauss open source community?

Eval and assert execute one sentence Trojan horse

Flutter 渲染机制——GPU线程渲染

Bandwidth and currency

借生态力量,openGauss突破性能瓶颈
随机推荐
Block, there is a gap between the block elements in the row
Database startup report error_ user_ connect_ times &gt; 0 error
containerd拉取私库镜像失败(kubelet)
All in one 1319 - queue for water
IBM3650M4实体机安装VCenter7.0
vCenter7.0管理Esxi7.0主机
Help send some recruitment. If you are interested, you can have a look
MCDF顶层验证方案
ERP生产作业控制 华夏
The response of the database interface is very slow
Risk control and application of informatization project
pytorch_demo1
How to log in multiple wechat on the computer
List delete collection elements
Fluent rendering mechanism - GPU thread rendering
数据库启动报error_user_connect_times &gt; 0错误
借生态力量,openGauss突破性能瓶颈
Use of "PHP Basics" delimiters
"PHP Basics" tags in PHP
PHP realizes data interaction with MySQL