当前位置:网站首页>Realization of background channel group management function
Realization of background channel group management function
2022-07-27 08:28:00 【qishaoawei】
What's up, channel group ? What is infinite classification ?、
Channel group : Distinguish according to a top-level category , Set group of the same transaction
Infinite classification : A class can be divided into several subclasses , Then a subclass can be divided into other subclasses, which is an infinite method .
Create model classes
In the project goods Sub application of models.py File
# List of commodity types
class Cate(models.Model):
name=models.CharField(' Category name ',max_length=30)
# Self correlation # Reverse queries can be called directly 'subs'
cid=models.ForeignKey('self',on_delete=models.CASCADE,related_name='subs',null=True,blank=True)
def __str__(self):
return self.name
class Meta:
db_table='goodscate'
verbose_name_plural=' List of commodity types '
# Sort and group ( Channel group )
class Group(models.Model):
name=models.CharField(' Channel group name ',max_length=30)
# # One to one relationship
cate=models.OneToOneField(Cate,on_delete=models.CASCADE,verbose_name=' Primary categories ')
group_url=models.CharField(' Address of the channel ',max_length=100,default='http://jd.com') # Default
sequence=models.IntegerField(' Display order ',default=0)
def __str__(self):
return self.name
class Meta:
db_table='cate_group'
verbose_name_plural=' Channel group '
Generate migration file , Migration
List of commodity categories cate Import data 
Classify and group according to the imported data ( Channel group )Group Add several pieces of data manually
notes : Fill in the data of the primary category
Write a serializer
Create... Under the sub application directory serializers.py File
from rest_framework import serializers
from .models import *
# Sort and group ( Channel group ) serializers
class GroupSer(serializers.ModelSerializer):
# # Only serialize output
cate_name=serializers.SerializerMethodField(read_only=True)
def get_cate_name(self,obj):
return obj.cate.name
class Meta:
model=Group
fields='__all__'
read_only_fields=['id']
# Serializer of product category
class GoodsCateSer(serializers.ModelSerializer):
class Meta:
model=Cate
fields='__all__'
read_only_fields=['id']
Write view classes
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView,ListAPIView
from .serializers import *
from .models import *
from rest_framework.pagination import PageNumberPagination
# Pager class
class MyPagination2(PageNumberPagination):
page_size = 2
max_page_size = 5
page_query_param = 'page'
page_size_query_param = 'pageSize'
# View of channel group
class ListCreateGroupAPIView(ListCreateAPIView):
queryset = Group.objects.all()
serializer_class = GroupSer
pagination_class = MyPagination2
class ReUpDeAPIViwe(RetrieveUpdateDestroyAPIView):
queryset = Group.objects.all()
serializer_class = GroupSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
# View of the first level category # Used for front-end access to foreign key data
class FirstCateAPIView(ListAPIView):
queryset = Cate.objects.filter(cid=None)
serializer_class = GoodsCateSer
Configure the routing
from django.urls import path
from .views import *
urlpatterns = [
# 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())
]
front end
Find the corresponding vue Components
Configure the relative functions
for example :Channels.vue
Configure data paging 
<script> import BreadCrumb from "@/components/widget/BreadCrumb"; // Add channel group import Addchannels from "@/components/widget/AddChannels"; // Exhibition , Delete , modify import ChannelsTable from "@/components/widget/ChannelsTable"; export default {
name: "Channels", data() {
return {
page: 1, total: 0, pagesize: 2, aChannelsList: [], }; }, components: {
BreadCrumb, Addchannels, ChannelsTable, }, mounted() {
this.fnGetData(1); }, methods: {
// get data fnGetData(num) {
this.axios .get("/v1/goods/channels/", {
params: {
page: num, pageSize: this.pageSize, }, headers: {
Authorization: "JWT " + localStorage.token, }, responseType: "json", }) .then((result) => {
this.aChannelsList = result.data.results; this.total=result.data.count }) .catch((err) => {
console.log(" Error in channel request ", err); }); }, fnGetPage(page){
this.page=page this.fnGetData(page) } }, }; </script>
Exhibition , modify , Delete channel group data
for example :ChannelsTable.vue
When the form is modified, the drop-down box realizes the selection of category content 
<script> let token = localStorage.token; export default {
name: 'OptionsTable', props:['channels'], data () {
return {
pop_show:false, group_type_list:[], category_list:[], ChannelsForm:{
cate:'', group_url:'', name:'', sequence:'', }, rulesChannelsForm:{
} } }, methods:{
// Click the method triggered when editing fnPopShow(id){
// this.pop_show by default false this.pop_show = true; this.edit_id = id; this.axios.get('/v1/goods/channels/'+this.edit_id+'/', {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
console.log(' Update the response of a channel group ',res); this.ChannelsForm.name = res.data.name; this.ChannelsForm.group_url = res.data.group_url; this.ChannelsForm.sequence = res.data.sequence; this.ChannelsForm.cate = res.data.cate }).catch(err=>{
console.log(err.response); }); }, // Submit submitForm(){
this.axios.put('/v1/goods/channels/'+this.edit_id+'/', this.ChannelsForm, {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json' }).then(res=>{
console.log(' Update the response of the channel ',res) if (res.status==200){
this.$message({
type: 'success', message: ' Channel modification succeeded !' }); this.pop_show = false; this.resetForm('ChannelsForm'); this.$emit('fnResetTable'); }else{
this.$message({
type: 'error', message: ' Channel modification failed !' }); } }).catch(err=>{
console.log(err.response); }) }, // Delete fnDelChannel(id){
this.edit_id = id; this.$confirm(' This action will delete the channel , Whether or not to continue ?', ' Tips ', {
confirmButtonText: ' determine ', cancelButtonText: ' Cancel ', type: 'warning' }).then(() => {
this.axios.delete('/v1/goods/channels/'+this.edit_id+'/',{
headers: {
'Authorization': 'JWT ' + token }, responseType:'json' }).then(res=>{
if (res.status==204){
this.$message({
type: 'success', message: ' Delete channel succeeded !' }); this.$emit('fnResetTable'); }else{
this.$message({
type:'error', message:' Delete failed ' }) } }).catch(err=>{
if(err.response.status==404){
this.$message({
type:'info', message:' Channel not found !' }); } }) }).catch(() => {
this.$message({
type: 'info', message: ' Delete cancelled ' }); }); }, // Get all categories fnGetCategories(){
this.axios.get('/v1/goods/channels/firstcates/', {
headers: {
'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
this.category_list = res.data; console.log(" Category >>>",this.category_list) }).catch(err=>{
console.log(err.response); }); }, resetForm(formName){
this.$refs[formName].resetFields(); } }, mounted(){
// Get classes grouped // this.fnGetChannelType(); // Get all the primary category information this.fnGetCategories(); } } </script>
Add data
for example :AddChannels.vue
When adding, the form can also use the drop-down box to select the binding category , In the same way as above
<script> // import cons from "@/components/constant"; let token = localStorage.token; export default {
name: "AddChannels", data() {
return {
pop_show: false, group_type_list: [], category_list:[], ChannelsForm: {
name: "", cate: "", group_url: "", sequence: "", }, rulesChannelsForm: {
}, }; }, methods: {
// Data submitted submitForm() {
this.axios.post('/v1/goods/channels/',this.ChannelsForm,{
headers:{
Authorization:'JWT'+localStorage.token }, responsetype:'json' }).then((result) => {
console.log(' Change the successful response ',result) if (result.status==201){
this.$message({
type:'success', message:' Add success ' }) // Hide dialog this.pop_show=false this.$refs['channelsForm'].restFields() this.$emit('fnResetTable') }else{
this.$message({
type:'error', message:' Add success ' }) } }).catch((err) => {
console.log(' Modify the failed response '+err) }); }, // Category group data fnGetChannelType() {
this.axios.get('/v1/goods/channels/firstcates/',{
headers:{
Authorization:'JWT'+localStorage.token }, responseType:'json' }).then((result) => {
console.log(' Get the response of the first level category '+result) this.category_list=result.data }).catch((err) => {
console.log(' Get the response of category failure '+err) }); }, }, // mount mounted() {
this.fnGetChannelType(); }, }; </script>
边栏推荐
- How to uninstall -- Qianxin secure terminal management system
- Solution to the program design of the sequence structure of one book (Chapter 1)
- 【目标检测】YOLOv6理论解读+实践测试VisDrone数据集
- Plato farm is expected to further expand its ecosystem through elephant swap
- JS basic exercises
- Flask one to many database creation, basic addition, deletion, modification and query
- JS basic knowledge - daily learning summary ①
- arguments
- pytorch_ demo1
- Development of three database general SQL code based on PG Oracle and MySQL
猜你喜欢

Massive data Xiao Feng: jointly build and govern opengauss root community and share a thriving new ecosystem
![[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation](/img/44/52c7dc6871fd43223eadfd394e159e.png)
[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation

Redis configuration file download

Breadth first search

Solve the problem of slow batch insertion of MySQL JDBC data

好吃难吃饱七分为宜;好喝难喝醉三分为佳

pytorch_ demo1

Alibaba cloud international receipt message introduction and configuration process

redis配置文件下载

After downloading URL loader and specifying the size of the image with limit, the image will not be displayed
随机推荐
Development of three database general SQL code based on PG Oracle and MySQL
Teach you to build a nail warning robot hand in hand
Use of string type "PHP Basics"
[netding cup 2020 rosefinch group]nmap 1 two solutions
Eval and assert execute one sentence Trojan horse
All in one 1319 - queue for water
vCenter7.0管理Esxi7.0主机
openGauss之TryMe初体验
regular expression
[applet] the upload of the wechat applet issued by uniapp failed error: error: {'errcode': -10008,'errmsg':'Invalid IP
containerd拉取私库镜像失败(kubelet)
Solution to the program design of the sequence structure of one book (Chapter 1)
Attack and defense World Lottery
Qt Creator代码风格插件Beautifier
Apache SSI remote command execution vulnerability
Virtual machine cloning
Alibaba cloud international receipt message introduction and configuration process
Chapter 2 foreground data display
After downloading URL loader and specifying the size of the image with limit, the image will not be displayed
opengauss从库停掉,发现主库无法写入数据