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": []
}]
}]

django中的构造字典(二级菜单,评论树,购物车)的更多相关文章

  1. django自定义rbac权限组件(二级菜单)

    一.目录结构 二.表结构设计 model.py from django.db import models # Create your models here. class Menu(models.Mo ...

  2. Html中鼠标悬停显示二级菜单的两种方法

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. DJANGO结合jQuery cxSelect 作二级菜单过滤

    EN,到这个阶段,基本功能算是完成了. 使用了jQuery cxSelect这个插件. http://code.ciaoca.com/jquery/cxselect/ 相关代码如下: html: &l ...

  4. Django--CRM--一级, 二级 菜单表

    一. 一级菜单表 1. 首先要修改权限表的字段, 在权限表下面加上icon和 is_menu 的字段 2. 展示结果 # 我们既然想要动态生成一级菜单,那么就需要从数据库中拿出当前登录的用户的菜单表是 ...

  5. django中动态生成二级菜单

    一.动态显示二级菜单 1.修改权限表结构 (1)分析需求,要求左侧菜单如下显示: 客户管理: 客户列表 账单管理: 账单列表 (2)修改rbac下的models.py,修改后代码如下: from dj ...

  6. django权限之二级菜单

    遗漏知识点 1.构建表结构时,谁被关联谁就是主表,在层级删除的时候,删除子表的时候,主表不会被删除,反之删除主表的话,字表也会被删除, 使用related_name=None   反向查询,起名用的 ...

  7. Django - 权限(4)- queryset、二级菜单的默认显示、动态显示按钮权限

    一.queryset Queryset是django中构建的一种数据结构,ORM查询集往往是queryset数据类型,我们来进一步了解一下queryset的特点. 1.可切片 使用Python 的切片 ...

  8. 巨蟒django之权限7:动态生成一级&&二级菜单

    内容回顾: . 权限的控制 . 表结构设计 存权限的信息 用户表 - name 用户名 - pwd 密码 - roles 多对多 角色表 - name - permissions 多对多 权限表 - ...

  9. Django - 权限(3)- 动态显示二级菜单

    一.动态显示二级菜单 上篇随笔中,我们实现了动态显示一级菜单,现在考虑这样一种情况,用户的菜单权限比较多,这个时候全部并列展现在左侧菜单就不合适了,所以,现在有这样一个需求,即把用户的菜单权限分类,划 ...

随机推荐

  1. Mysql 游标的定义与使用方式

    创建游标: 首先在MySql中创建一张数据表: CREATE TABLE IF NOT EXISTS `store` (   `id` int(11) NOT NULL AUTO_INCREMENT, ...

  2. cannot focus element解决方案

    If you enconter error "cannot focus element" when using Selenium+Python in Chrome to input ...

  3. list 增 删 改 查 及 公共方法

    # 热身题目:增加名字,并且按q(不论大小写)退出程序 li = ['taibai','alex','wusir','egon','女神'] while 1: username = input('&g ...

  4. [转]LazyLoad.js及scrollLoading.js

    本文转自:http://blog.csdn.net/ning109314/article/details/7042829 目前图片延迟加载主要分两大块,一是触发加载(根据滚动条位置加载图片):二是自动 ...

  5. PyCharm5 破解汉化

    作者博文地址:https://www.cnblogs.com/liu-shuai/ 破解: 将下列序列号复制到软件激活界面即可破解. 43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0 ...

  6. jeecg3.8popup弹出窗口触发失去焦点事件,引发验证弹窗,影响体验问题的解决办法

    在初始化表单的代码中添加以下加粗部分,有几个popup就定义几个标志位,主要是防止第一次失去焦点时候的弹窗(此时还未来得及选择),提交表单的时候还是会正常校验的. //popup触发失去焦点事件,设置 ...

  7. springboot2.x如何添加事务

    什么时候需要添加事务呢?一般情况下,如果该方法有两条SQL语句或者以上都需要添加(个人感觉:)). 首先需要在我们的启动类加上 @EnableTransactionManagement //开启事务管 ...

  8. intellijidea课程 intellijidea神器使用技巧 3-1 列操作

    Ctrl shift 右箭头 ==> 选中右边单词 ctrl shift alt L ==> 选中所有相同的字符 Ctrl alt L     ==> 格式化

  9. SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1fa5519] was not registered for synchronization because synchronization is not active

    Creating a new SqlSessionSqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1fa5519] w ...

  10. git 提交各种情况下的处理方式

    自己总结: 01.若在提交过程中有冲突,解决冲突后,git add . git rebase —continue git push for   02.git rebase vs git merge g ...