django中的构造字典(二级菜单,评论树,购物车)

1.构造父子结构:

1.1需求样式

客户列表 customer_list /customer/list/
-----> 添加客户 customer_add /customer/add/
-----> 编辑客户 customer_edit /customer/edit/(?P<cid>\d+)/
-----> 删除客户 customer_del /customer/del/(?P<cid>\d+)/
-----> 批量导入客户 customer_import /customer/import/
-----> 下载客户模板 customer_tpl /customer/tpl/
账单列表 payment_list /payment/list/
-----> 添加账单 payment_add /payment/add/
-----> 编辑账单 payment_edit /payment/edit/(?P<pid>\d+)/
-----> 删除账单 payment_del /payment/del/(?P<pid>\d+)/

django中构造方式:  ———>最重要的其实就是这里对于表结构的考虑

{
    1:{
        'title':'账单列表',
        'url':'/payment/list/',
        'name':'payment_list',
        children:[
            {'title':'删除账单','url':'/payment/list/','name':'payment_list'},
            {'title':'编辑账单','url':'/payment/list/','name':'payment_list'},
            {'title':'添加账单','url':'/payment/list/','name':'payment_list'},
        ]
    },
     2:{
        'title':'客户列表',
        'url':'/payment/list/',
        'name':'payment_list',
        children:[
            {'title':'下载客户模板','url':'/payment/list/','name':'payment_list'},
            {'title':'下载客户模板','url':'/payment/list/','name':'payment_list'},
            {'title':'下载客户模板','url':'/payment/list/','name':'payment_list'},
        ]
    }
}

models.py

class Menu(models.Model):
    """
    菜单表
    """
    title = models.CharField(max_length=32,unique=True)
    icon = models.CharField(max_length=32) 

    def __str__(self):
        return self.title

class Permission(models.Model):
    """
    权限表
    """
    title = models.CharField(verbose_name='标题', max_length=32)
    url = models.CharField(verbose_name='含正则的URL', max_length=128)
    name = models.CharField(verbose_name='URL别名',max_length=32,null=True,blank=True)
    parent = models.ForeignKey(verbose_name='父权限',to='Permission',null=True,blank=True)
    menu = models.ForeignKey(verbose_name='菜单',to='Menu',null=True,blank=True)

    def __str__(self):
        return self.title

# 有parent_id没有menu_id表示是具有三级菜单
# 有menu_id没有parent_id则表示是具有二级菜单
# 两者不能同时都有值

表数据

menu:

permission:

构造方式一:

def role_bbb(request):
    permission_queryset = models.Permission.objects.all().values("id","title","url","name","parent_id")
    root_permission_dict = {}

    for item in permission_queryset:
        if not item["parent_id"]:
            root_permission_dict[item["id"]] = {
                    "url":item["url"],
                    "title":item["title"],
                    "name":item["name"],
                    "children":[],
                }

    for item in permission_queryset:
        parent_id = item['parent_id']

        if parent_id:
            root_permission_dict[parent_id]['children'].append({
                'title': item['title'],
                'url': item['url'],
                'name': item['name']
            })

    # 打印测试
    for root in root_permission_dict.values():
        print(root["title"],root['name'],root['url'])

        for node in root['children']:
            print('----->', node['title'], node['name'], node['url'])

    return HttpResponse("+++++")

构造方式二:

def role_bbb(request):
    root_permission_dict = {}
    query = models.Permission.objects.filter(menu__isnull=False).values('id','title','url','name','parent_id')
    for item in query:
        root_permission_dict[item["id"]] = {
            'title': item['title'],
            'url': item['url'],
            'name': item['name'],
            'children': []
        }

    models.Permission.objects.filter(menu__isnull=True).values('id','title','url','name','parent_id')
    for item in query_dic:
        parent_id = item['parent_id']
        if parent_id:
            root_permission_dict[parent_id]['children'].append({
                'title': item['title'],
                'url': item['url'],
                'name': item['name']
            })

    # 打印测试
    for root in root_permission_dict.values():
        print(root["title"],root['name'],root['url'])

        for node in root['children']:
            print('----->', node['title'], node['name'], node['url'])

    return HttpResponse("+++++")

 构造方式三:

def role_bbb(request):
    permission_queryset = models.Permission.objects.all().values("id", "title", "url", "name", "parent_id")
    root_permission_dict = {}
    for item in permission_queryset:
        if not item['parent_id']:
            root_permission_dict[item['id']] = {
                'title': item['title'],
                'url': item['url'],
                'name': item['name'],
                'children': []  
            }
        else:
            pid = item["parent_id"]
            root_permission_dict[pid]["children"].append({
                'title': item['title'],
                'url': item['url'],
                'name': item['name']
            })

    return HttpResponse("+++++")

2.构造家族结构   ------>用于构造评论树

2.1需求

  在实际应用中,我们对于一篇文章的评论通常包含了根评论,根评论下可以具有多个子评论,我们现在才可以通过构造数据结构来实现他所具有的功能

构造方式:

comment_list = [
    {'id': 1, 'title': '根评论', 'pid': None},
    {'id': 2, 'title': '根评论', 'pid': None},
    {'id': 3, 'title': 'id是1下的评论', 'pid': 1},
    {'id': 4, 'title': 'id是2下的评论', 'pid': 2},
    {'id': 5, 'title': 'id是1下的评论', 'pid': 1},
    {'id': 6, 'title': 'id是3下的评论', 'pid': 3},
    {'id': 7, 'title': 'id是6下的评论', 'pid': 6},
]

演示代码:

comment_dict = {}
for item in comment_list:
    item['children'] = []
    comment_dict[item['id']] = item


for row in comment_list:
    if not row['pid']:  # 判断根评论
        continue  # 跳过此次循环
    pid = row['pid']  # 获取pid
    # 最加到children中
    comment_dict[pid]['children'].append(row)

print(comment_dict)

效果:

{
    1: {
        'id': 1,
        'title': '根评论',
        'pid': None,
        'children': [{
            'id': 3,
            'title': 'id是1下的评论',
            'pid': 1,
            'children': [{
                'id': 6,
                'title': 'id是3下的评论',
                'pid': 3,
                'children': [{
                    'id': 7,
                    'title': 'id是6下的评论',
                    'pid': 6,
                    'children': []
                }]
            }]
        }, {
            'id': 5,
            'title': 'id是1下的评论',
            'pid': 1,
            'children': []
        }]
    },
    2: {
        'id': 2,
        'title': '根评论',
        'pid': None,
        'children': [{
            'id': 4,
            'title': 'id是2下的评论',
            'pid': 2,
            'children': []
        }]
    },
    3: {
        'id': 3,
        'title': 'id是1下的评论',
        'pid': 1,
        'children': [{
            'id': 6,
            'title': 'id是3下的评论',
            'pid': 3,
            'children': [{
                'id': 7,
                'title': 'id是6下的评论',
                'pid': 6,
                'children': []
            }]
        }]
    },
    4: {
        'id': 4,
        'title': 'id是2下的评论',
        'pid': 2,
        'children': []
    },
    5: {
        'id': 5,
        'title': 'id是1下的评论',
        'pid': 1,
        'children': []
    },
    6: {
        'id': 6,
        'title': 'id是3下的评论',
        'pid': 3,
        'children': [{
            'id': 7,
            'title': 'id是6下的评论',
            'pid': 6,
            'children': []
        }]
    },
    7: {
        'id': 7,
        'title': 'id是6下的评论',
        'pid': 6,
        'children': []
    }
}

  这样可以构造,但是明显显得累赘,把子评论也全都打印了一遍

以上在做改进:

comment_dict = {}
for item in comment_list:
    item['children'] = []
    comment_dict[item['id']] = item


result = []  
for row in comment_list:
    if not row['pid']:  # 判断根评论
        result.append(row)  # 添加到列表
    else:
        pid = row['pid'] 
        # 最加到children中
        comment_dict[pid]['children'].append(row)

print(result)

json序列化效果(想使用序列化格式工具转化,需要先转换成json格式才行,通过json.dumps):

[{
    "title": "根评论",
    "pid": null,
    "id": 1,
    "children": [{
        "title": "id是1下的评论",
        "pid": 1,
        "id": 3,
        "children": [{
            "title": "id是3下的评论",
            "pid": 3,
            "id": 6,
            "children": [{
                "title": "id是6下的评论",
                "pid": 6,
                "id": 7,
                "children": []
            }]
        }]
    }, {
        "title": "id是1下的评论",
        "pid": 1,
        "id": 5,
        "children": []
    }]
}, {
    "title": "根评论",
    "pid": null,
    "id": 2,
    "children": [{
        "title": "id是2下的评论",
        "pid": 2,
        "id": 4,
        "children": []
    }]
}]

 

posted @ 2018-07-23 15:20  -Learning-  阅读(406)  评论(0编辑  收藏  举报