当前位置:网站首页>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
边栏推荐
- Flutter 渲染机制——GPU线程渲染
- JS basic knowledge - daily learning summary ①
- JS advanced knowledge - function
- 第2章 前台数据展现
- All in one 1329 cells (breadth first search)
- [target detection] yolov6 theoretical interpretation + practical test visdrone data set
- My senior
- 说透缓存一致性与内存屏障
- Software test interview questions (key points)
- Virtual machine cloning
猜你喜欢

OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)

Massive data Xiao Feng: jointly build and govern opengauss root community and share a thriving new ecosystem

ERP生产作业控制 华夏

Ubuntu: install PostgreSQL

Bandwidth and currency

Process control - Branch

Breadth first search

idea远程调试

Chapter 2 foreground data display

情人节,我用字符画出了一个对象!
随机推荐
[target detection] yolov6 theoretical interpretation + practical test visdrone data set
Massive data Xiao Feng: jointly build and govern opengauss root community and share a thriving new ecosystem
百人参与,openGauss开源社区这群人都在讨论什么?
Dirsearch[directory scanning tool]
Map structure
Idea remote debugging
I drew a Gu ailing with characters!
Teach you to build a nail warning robot hand in hand
虚拟机克隆
ERP production operation control Huaxia
Breadth first search
1176 questions of Olympiad in informatics -- who ranked K in the exam
Attack and defense world MFW
OPPO 自研大规模知识图谱及其在数智工程中的应用
JS basic knowledge - daily learning summary ①
Functions and arrow functions
Plato farm is expected to further expand its ecosystem through elephant swap
redis配置文件下载
Shenzhi Kalan Temple
[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation