当前位置:网站首页>Realize SPU management in the background
Realize SPU management in the background
2022-07-27 08:29:00 【qishaoawei】
brief introduction
Actually, it should be configured first spu In the configuration sku
According to the textbook, it's upside down
Configure model classes
Follow configuration sku Like my blog
It is related to the brand table and the commodity category table
from django.db import models
# spu surface
class SPUS(models.Model):
name=models.CharField('spu',max_length=20)
# # Bind brand table
brand=models.ForeignKey(Brand,on_delete=models.CASCADE,verbose_name=' Brand ')
# # List of commodity types # Reverse queries can be called directly
category1=models.ForeignKey(Cate,on_delete=models.CASCADE,related_name='cate1_spu',verbose_name=' Primary categories ')
category2=models.ForeignKey(Cate,on_delete=models.CASCADE,related_name='cate2_spu',verbose_name=' Level 2 categories ')
category3=models.ForeignKey(Cate,on_delete=models.CASCADE,related_name='cate3_spu',verbose_name=' Level III category ')
comment_num=models.IntegerField(' Comment quantity ',default=0)
sales=models.IntegerField(' sales ',default=0)
desc_detail=models.TextField(' Detailed description ',default='')
desc_pack=models.TextField(' Packaging information ',default='')
desc_service=models.TextField(' After-sales service ',default='')
def __str__(self):
return self.name
class Meta:
db_table='spu'
# 'sku' Commodity list
class SKUS(models.Model):
name=models.CharField('sku',max_length=100)
describe=models.CharField(' Commodity Description ',max_length=500)
price=models.DecimalField(' Price ',decimal_places=2,max_digits=8)
stick=models.IntegerField(' stock ',default=0)
sales=models.IntegerField(' sales ',default=0)
detail=models.TextField(' details ',default='')
image_default=models.CharField(' The default image ',max_length=300,default='')
is_selling=models.BooleanField(' Are you selling ',default=True) # Boolean type
# # Bind the product category table
cate=models.ForeignKey(Cate,on_delete=models.CASCADE,verbose_name=' Primary categories ')
# # binding spu surface
spu=models.ForeignKey(SPUS,on_delete=models.CASCADE,verbose_name=' Belongs to SPU')
def __str__(self):
return self.name
class Meta:
db_table='sku'
verbose_name_plural=' goods sku'
Create a serializer
from rest_framework import serializers
from .models import *
#SKU Serializer of model class
class SKUSer(serializers.ModelSerializer):
cate_name=serializers.SerializerMethodField(read_only=True)
def get_cate_name(self,obj):
return obj.cate.name
class Meta:
model=SKUS
fields='__all__'
read_only_fields=['id','detail','image_default','sales']
#SPU Serializer of model class
class SPUSer(serializers.ModelSerializer):
brand_name=serializers.SerializerMethodField(read_only=True)
def get_brand_name(self,obj):
return obj.brand.name
class Meta:
model=SPUS
fields='__all__'
read_only_fields=['id']
Write view classes
The view of child categories is based on id Get corresponding id All data under
Class A , second level , Level three cate List of commodity types
# View of child categories
class SubCatesAPIView(RetrieveUpdateDestroyAPIView):
queryset = Cate.objects.all()
serializer_class = GoodsCateSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
def retrieve(self, request, *args, **kwargs):
# Get the parent class object
# /v1/goods/channels/subCate/1/
parent_obj=self.get_object()
# According to the parent category , Get child categories
subs_queryset=parent_obj.subs.all()
# Subclass serialization
ser=self.get_serializer(subs_queryset,many=True)
# Return response
return Response(ser.data)
# sku View set
class SKUAPIView(ModelViewSet):
queryset = SKUS.objects.all()
serializer_class = SKUSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
#spu The view of
class SPUAPIView(ModelViewSet):
queryset = SPUS.objects.all()
serializer_class = SPUSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
pagination_class = MyPagination
# Another view that loads all brands , Avoid data incompleteness caused by the pager
class BarabdsAllAPIView(ListAPIView):
queryset = Brand.objects.all()
serializer_class = BrandSer
Configure the routing
from django.urls import path
from rest_framework import routers
from .views import *
urlpatterns = [
# Upload logo
# Interface of channel group , Get all 、 Add a new one
path('channels/',ListCreateGroupAPIView.as_view()),
# Interface of channel group , retrieval , change , Delete
path('channels/<int:pk>/',ReUpDeAPIViwe.as_view()),
# Load all first level categories
path('channels/firstcates/',FirstCateAPIView.as_view()),
# Load child categories
path('channels/subCates/<int:pk>/',SubCatesAPIView.as_view()),
# Load all brand data
path('brands/all/',BarabdsAllAPIView.as_view()),
]
# Brand routing
router=routers.SimpleRouter()
router.register('brands',BrandViewSet,'brands')
router.register('skus',SKUAPIView,'skus')
router.register('spus',SPUAPIView,'spus')
urlpatterns+=router.urls
front end
Find the corresponding veu Components , To configure
Realization sku Addition, deletion and modification of
for example :Spu.vue Get all the data
<script> import BreadCrumb from '@/components/widget/BreadCrumb' import SpuTable from '@/components/widget/SpuTable' export default {
name: 'Spu', data () {
return {
page:1, pages:8, total:0, pagesize:10, aSpuList:[] } }, components:{
BreadCrumb, SpuTable }, mounted(){
this.fnGetData(1); }, methods:{
// obtain spu data fnGetData:function(num){
this.axios.get('/v1/goods/spus/',{
params:{
page:num, pageSize:this.pagesize }, headers:{
Authorization:'JWT'+localStorage.token }, responseType:'josn' }).then((result) => {
this.aSpuList=result.data.results this.total=result.data.count }).catch((err) => {
console.log(' obtain SPU Failure ',err.response.data) }); }, // Get paged data fnGetPage:function(dat){
} } } </script>
for example :SpuTable.vue Display and modify data
Modify the route in the event , Field etc.
<script> let token = localStorage.token; export default {
name: 'SkuTable', props:['spus'], data () {
return {
edit_id:'' } }, methods:{
fnDelSpu(id){
this.edit_id = id; this.$confirm(' This action will delete the SPU, Whether or not to continue ?', ' Tips ', {
confirmButtonText: ' determine ', cancelButtonText: ' Cancel ', type: 'warning' }).then(() => {
this.axios.delete('/v1/goods/spus/'+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:' Item not found !' }); } }) }).catch(() => {
this.$message({
type: 'info', message: ' Delete cancelled ' }); }); } } } </script>
for example :SpuEdit.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; import tinymce from "tinymce/tinymce"; import Editor from "@tinymce/tinymce-vue"; import "tinymce/themes/modern/theme"; import "tinymce/plugins/media"; import "tinymce/plugins/table"; import "tinymce/plugins/lists"; import "tinymce/plugins/contextmenu"; import "tinymce/plugins/wordcount"; import "tinymce/plugins/colorpicker"; import "tinymce/plugins/textcolor"; import BreadCrumb from "@/components/widget/BreadCrumb"; export default {
name: "SpuAdd", data() {
return {
pop_show: false, edit_id: "", upload_img_url: "/static/images/pic_bg.png", btn_text: " Submit ", init: {
language_url: "/static/tinymce/langs/zh_CN.js", language: "zh_CN", skin_url: "/static/tinymce/skins/lightgray", width: "99%", height: 200, branding: false, menubar: false, plugins: "lists image media table textcolor wordcount contextmenu", toolbar: "undo redo | styleselect | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists media table | removeformat", }, brand_list: [], category1_list: [], category2_list: [], category3_list: [], SpuForm: {
name: "", brand: "", // brand id category1: "", // First class id category2: "", // Secondary category id category3: "", // Third class id desc_detail: "", desc_pack: "", desc_service: "", brand_name: "", }, }; }, components: {
BreadCrumb, Editor, }, methods: {
// Get specified spu Information fnGetThisSPU() {
this.axios.get('/v1/goods/spus/'+this.edit_id+'/',{
headers:{
Authorization:'JWT'+localStorage.token }, responseType:'json' }).then((result) => {
console.log(' Load the specified SPU',result) this.SpuForm=result.data this.category2_list=this.fnGetCategory_sub(result.data.category1,2) this.category3_list=this.fnGetCategory_sub(result.data.category2,3) }).catch((err) => {
console.log(' Request to load the specified SPU error ',err.response.data) }); }, // Get all brands fnGetBrand: function () {
this.axios.get('/v1/goods/brands/all/',{
headers:{
Authorization:'JWT '+token }, responseType:'json' }).then((result) => {
this.brand_list=result.data }).catch((err) => {
console.log(' Error loading all brands ',err.response.data) }); }, // Get the first level category fnGetCategories: function () {
this.axios.get('/v1/goods/channels/firstcates/',{
headers:{
Authorization:'JWT'+localStorage.token }, responseType:'json' }).then((result) => {
this.category1_list=result.data }).catch((err) => {
console.log(' Request level 1 category error ',err.response.data) }); }, // Get level 2 Three levels of classification TODO Classified according to the first level id Get secondary classification ; According to secondary classification id Get three-level classification fnGetCategory_sub: function (sid, num) {
this.axios .get("/v1/goods/channels/subCates/" + sid + "/", {
headers: {
Authorization: "JWT " + token, }, responseType: "json", }) .then((res) => {
this["category" + num + "_list"] = res.data; }) .catch((err) => {
console.log(err); }); }, submitForm() {
this.axios .put("/v1/goods/spus/" + this.edit_id + "/", this.SpuForm, {
headers: {
Authorization: "JWT " + token, }, responseType: "json", }) .then((dat) => {
if (dat.status == 200) {
this.$message({
type: "success", message: "SPU Modification successful !", }); setTimeout(() => {
this.$router.push({
path: "/home/spu" }); }, 2000); } }) .catch((err) => {
if (err.response.status == 400) {
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], }); } } }); }, }, mounted() {
tinymce.init({
}); // Brand acquisition this.fnGetBrand(); // Get category this.fnGetCategories(); // Receive the to be modified id this.edit_id = this.$route.params.sEdit_id; // Get specified id Categories this.fnGetThisSPU(); }, }; </script>
边栏推荐
- docker 安装mysql后进入容器内部发现登录不了mysql
- Functions and arrow functions
- Opengauss stopped from the library and found that the main library could not write data
- [MRCTF2020]PYWebsite 1
- Redis configuration file download
- Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering
- 好吃难吃饱七分为宜;好喝难喝醉三分为佳
- The response of the database interface is very slow
- Demo:st05 find text ID information
- File name wildcard rules for kettle
猜你喜欢

Demo:st05 find text ID information

Design and development of GUI programming for fixed-point one click query

idea远程调试

"PHP Basics" PHP statements and statement blocks

How to play with the purchase of SAP variant materials? Look at this article and you will understand

Attack and defense World Lottery

Idea remote debugging

What is the real HTAP? (1) Background article

PHP realizes data interaction with MySQL

First experience of tryme in opengauss
随机推荐
Map structure
STM32小bug汇总
Shenzhi Kalan Temple
Have a good laugh
vCenter7.0管理Esxi7.0主机
JS rotation chart
Use of "PHP Basics" delimiters
Fluent rendering mechanism - GPU thread rendering
【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发1/100
[MRCTF2020]PYWebsite 1
[netding cup 2020 rosefinch group]nmap 1 two solutions
Design and development of GUI programming for fixed-point one click query
[golang] golang develops wechat official account web page authorization function
You may need an additional loader to handle the result of these loaders.
Record a PG master-slave setup and data synchronization performance test process
The third letter to the little sister of the test | Oracle stored procedure knowledge sharing and test instructions
MCDF顶层验证方案
Hundreds of people participated. What are these people talking about in the opengauss open source community?
1176 questions of Olympiad in informatics -- who ranked K in the exam
STM32 small bug summary