zoukankan      html  css  js  c++  java
  • drf 三级菜单后台序列化以及数据库的设计

    第一种,

    model.py结构:

    class GoodsCategory(models.Model):
        """
        商品类别
        """
        CATEGORY_TYPE = (
            (1, "一级类目"),
            (2, "二级类目"),
            (3, "三级类目"),
        )
        name = models.CharField(default="", max_length=30, verbose_name="类别名", help_text="类别名")
        code = models.CharField(default="", max_length=30, verbose_name="类别code", help_text="类别code")
        desc = models.TextField(default="", verbose_name="类别描述", help_text="类别描述")
    category_type
    = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="类目级别", help_text="类目级别") parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name="父类目级别", help_text="父目录", related_name="sub_cat")

    看下这个视图设置,

    class CategoryView(ListAPIView):
        '''
        全部分类
        '''
        queryset = GoodsCategory.objects.filter(category_type=1)
        serializer_class = CategorySerializer

    第二种:

    也可以这样设计数据库:

    class GoodsCategory(BaseModel):
     # """
     # 商品类别
     # """
        name = models.CharField(max_length=10, verbose_name='名称')
        parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, verbose_name='⽗类别',related_name='sub_cat')
        class Meta:
            db_table = 'tb_goods_category'
            verbose_name = '商品类别'
            verbose_name_plural = verbose_name
        def __str__(self):
            return self.name

    视图这样写:

    class CategoryInfoView(mixins.ListModelMixin,GenericAPIView):
        queryset = GoodsCategory.objects.filter(parent=None)
        serializer_class = CategorySerializer
        def get(self,request):
            return self.list(request)

    因为第一级目录的父级是None,然后以这个为条件实现查询,有点像三级联动数据库的设计

    序列化实现充分用的是数据库反查,related_name设置。

    from rest_framework import serializers
    from .models import GoodsCategory
    
    class CategorySerializer3(serializers.ModelSerializer):
        class Meta:
            model = GoodsCategory
            fields = "__all__"
    
    
    class CategorySerializer2(serializers.ModelSerializer):
        sub_cat = CategorySerializer3(many=True)
        class Meta:
            model = GoodsCategory
            fields = "__all__"
    
    
    class CategorySerializer(serializers.ModelSerializer):
        sub_cat = CategorySerializer2(many=True)
        class Meta:
            model = GoodsCategory
            fields = "__all__"

     数据结构如下展示:

  • 相关阅读:
    Hbase常用Shell命令
    Hbase的安装与基本操作
    Unity3d 游戏设计(一)井字棋
    Unity3d 二、离散仿真引擎基础
    Unity3D 一、游戏
    String StringBuffer StringBulider
    Java日志记录log4j最简明教程
    使用PinYin4j.jar将汉字转换为拼音
    线性素数筛
    求一个数的约数个数 d(n)
  • 原文地址:https://www.cnblogs.com/lvye001/p/10214830.html
Copyright © 2011-2022 走看看