当前位置:网站首页>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
边栏推荐
- Iterators and generators
- 面试官:什么是脚手架?为什么需要脚手架?常用的脚手架有哪些?
- [MRCTF2020]PYWebsite 1
- First experience of tryme in opengauss
- UVM Introduction Experiment 1
- [NPUCTF2020]ReadlezPHP 1
- Is redis really slowing down?
- Database startup report error_ user_ connect_ times &gt; 0 error
- List delete collection elements
- "PHP Basics" uses echo statements to output information
猜你喜欢

Virtual machine cloning

Translation character '/b' in C #

第2章 前台数据展现

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

"PHP Basics" uses echo statements to output information
![[MRCTF2020]PYWebsite 1](/img/d4/2d9cd06abd7188add668cde77d3075.png)
[MRCTF2020]PYWebsite 1

Block, there is a gap between the block elements in the row

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

百人参与,openGauss开源社区这群人都在讨论什么?

情人节,我用字符画出了一个对象!
随机推荐
arguments
Dasctf2022.07 enabling game password WP
Functions and arrow functions
Data extraction 2
[BJDCTF2020]EasySearch 1
redis配置文件下载
[netding cup 2020 rosefinch group]nmap 1 two solutions
Login to homepage function implementation
Shenzhi Kalan Temple
File name wildcard rules for kettle
Database startup report error_ user_ connect_ times &gt; 0 error
Idea remote debugging
Element display mode: block level, inline, inline block, nesting specification, display mode conversion
[NPUCTF2020]ReadlezPHP 1
OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)
Demo:st05 find text ID information
"Intermediate and advanced test questions": what is the implementation principle of mvcc?
idea远程调试
百人参与,openGauss开源社区这群人都在讨论什么?
DEMO:ST05 找文本ID 信息