Django中使用 Closure Table 储存无限分级数据
作者:栖迟于一丘 发布时间:2021-05-25 03:05:07
标签:django,Closure,Table,分级数据
这篇文章给大家介绍Django中使用 Closure Table 储存无限分级数据,具体内容如下所述:
起步
对于数据量大的情况(比如用户之间有邀请链,有点 * 分销的意思),就要用到 closure table 的结构来进行存储。那么在 Django 中如何处理这个结构的模型呢?
定义模型
至少是要两个模型的,一个是存储分类,一个储存分类之间的关系:
class Category(models.Model):
name = models.CharField(max_length=31)
def __str__(self):
return self.name
class CategoryRelation(models.Model):
ancestor = models.ForeignKey(Category, null=True, related_name='ancestors', on_delete=models.SET_NULL, db_constraint=False, verbose_name='祖先')
descendant = models.ForeignKey(Category,null=True, related_name='descendants', on_delete=models.SET_NULL,
db_constraint=False, verbose_name='子孙')
distance = models.IntegerField()
class Meta:
unique_together = ("ancestor", "descendant")
数据操作
获得所有后代节点
class Category(models.Model):
...
def get_descendants(self, include_self=False):
"""获得所有后代节点"""
kw = {
'descendants__ancestor' : self
}
if not include_self:
kw['descendants__distance__gt'] = 0
qs = Category.objects.filter(**kw).order_by('descendants__distance')
return qs获得直属下级
class Category(models.Model):
...
def get_children(self):
"""获得直属下级"""
qs = Category.objects.filter(descendants__ancestor=self, descendants__distance=1)
return qs
节点的移动
节点的移动是比较难的,在 [ https://www.percona.com/blog/2011/02/14/moving-subtrees-in-closure-table/][1 ] 中讲述了,利用django能够执行原生的sql语句进行:
def add_child(self, child):
"""将某个分类加入本分类,"""
if CategoryRelation.objects.filter(ancestor=child, descendant=self).exists() \
or CategoryRelation.objects.filter(ancestor=self, descendant=child, distance=1).exists():
"""child不能是self的祖先节点 or 它们已经是父子节点"""
return
# 如果表中不存在节点自身数据
if not CategoryRelation.objects.filter(ancestor=child, descendant=child).exists():
CategoryRelation.objects.create(ancestor=child, descendant=child, distance=0)
table_name = CategoryRelation._meta.db_table
cursor = connection.cursor()
cursor.execute(f"""
DELETE a
FROM
{table_name} AS a
JOIN {table_name} AS d ON a.descendant_id = d.descendant_id
LEFT JOIN {table_name} AS x ON x.ancestor_id = d.ancestor_id
AND x.descendant_id = a.ancestor_id
WHERE
d.ancestor_id = {child.id}
AND x.ancestor_id IS NULL;
""")
cursor.execute(f"""
INSERT INTO {table_name} (ancestor_id, descendant_id, distance)
SELECT supertree.ancestor_id, subtree.descendant_id,
supertree.distance+subtree.distance+1
FROM {table_name} AS supertree JOIN {table_name} AS subtree
WHERE subtree.ancestor_id = {child.id}
AND supertree.descendant_id = {self.id};
""")
节点删除
节点删除有两种操作,一个是将所有子节点也删除,另一个是将自己点移到上级节点中。
扩展阅读
[ https://www.percona.com/blog/2011/02/14/moving-subtrees-in-closure-table/][2 ]
[ http://technobytz.com/closure_table_store_hierarchical_data.html][3 ]
完整代码
class Category(models.Model):
name = models.CharField(max_length=31)
def __str__(self):
return self.name
def get_descendants(self, include_self=False):
"""获得所有后代节点"""
kw = {
'descendants__ancestor' : self
}
if not include_self:
kw['descendants__distance__gt'] = 0
qs = Category.objects.filter(**kw).order_by('descendants__distance')
return qs
def get_children(self):
"""获得直属下级"""
qs = Category.objects.filter(descendants__ancestor=self, descendants__distance=1)
return qs
def get_ancestors(self, include_self=False):
"""获得所有祖先节点"""
kw = {
'ancestors__descendant': self
}
if not include_self:
kw['ancestors__distance__gt'] = 0
qs = Category.objects.filter(**kw).order_by('ancestors__distance')
return qs
def get_parent(self):
"""分类仅有一个父节点"""
parent = Category.objects.get(ancestors__descendant=self, ancestors__distance=1)
return parent
def get_parents(self):
"""分类仅有一个父节点"""
qs = Category.objects.filter(ancestors__descendant=self, ancestors__distance=1)
return qs
def remove(self, delete_subtree=False):
"""删除节点"""
if delete_subtree:
# 删除所有子节点
children_queryset = self.get_descendants(include_self=True)
for child in children_queryset:
CategoryRelation.objects.filter(Q(ancestor=child) | Q(descendant=child)).delete()
child.delete()
else:
# 所有子节点移到上级
parent = self.get_parent()
children = self.get_children()
for child in children:
parent.add_chile(child)
# CategoryRelation.objects.filter(descendant=self, distance=0).delete()
CategoryRelation.objects.filter(Q(ancestor=self) | Q(descendant=self)).delete()
self.delete()
def add_child(self, child):
"""将某个分类加入本分类,"""
if CategoryRelation.objects.filter(ancestor=child, descendant=self).exists() \
or CategoryRelation.objects.filter(ancestor=self, descendant=child, distance=1).exists():
"""child不能是self的祖先节点 or 它们已经是父子节点"""
return
# 如果表中不存在节点自身数据
if not CategoryRelation.objects.filter(ancestor=child, descendant=child).exists():
CategoryRelation.objects.create(ancestor=child, descendant=child, distance=0)
table_name = CategoryRelation._meta.db_table
cursor = connection.cursor()
cursor.execute(f"""
DELETE a
FROM
{table_name} AS a
JOIN {table_name} AS d ON a.descendant_id = d.descendant_id
LEFT JOIN {table_name} AS x ON x.ancestor_id = d.ancestor_id
AND x.descendant_id = a.ancestor_id
WHERE
d.ancestor_id = {child.id}
AND x.ancestor_id IS NULL;
""")
cursor.execute(f"""
INSERT INTO {table_name} (ancestor_id, descendant_id, distance)
SELECT supertree.ancestor_id, subtree.descendant_id,
supertree.distance+subtree.distance+1
FROM {table_name} AS supertree JOIN {table_name} AS subtree
WHERE subtree.ancestor_id = {child.id}
AND supertree.descendant_id = {self.id};
""")class CategoryRelation(models.Model): ancestor = models.ForeignKey(Category, null=True, related_name='ancestors', on_delete=models.SET_NULL, db_constraint=False, verbose_name='祖先') descendant = models.ForeignKey(Category,null=True, related_name='descendants', on_delete=models.SET_NULL, db_constraint=False, verbose_name='子孙') distance = models.IntegerField()
class Meta:
unique_together = ("ancestor", "descendant")[1]: https://www.percona.com/blog/2011/02/14/moving-subtrees-in-closure-table/
[2]: https://www.percona.com/blog/2011/02/14/moving-subtrees-in-closure-table/
[3]: http://technobytz.com/closure_table_store_hierarchical_data.html
总结
以上所述是小编给大家介绍的Django中使用 Closure Table 储存无限分级数据网站的支持!
来源:https://www.hongweipeng.com/index.php/archives/1802/
0
投稿
猜你喜欢
- jxdawei的blog:http://www.iwcn.net/本文讨论的是在web标准普及的形势下,网站程序员的定位以及如何与设计师配合
- 本文实例为大家分享了用户登录系统python实现代码,供大家参考,具体内容如 * 意事项: 1、使用python3执行程序。按提示输入1或2,
- 前言虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Req
- 1、前言前面讲到unittest里面setUp可以在每次执行用例前执行,这样有效的减少了代码量,但是有个弊端,比如打开浏览器操作,每次执行用
- 阅读上一篇:垂直栅格与渐进式行距(上) 新问题来也匆匆,去也“冲冲”。距上次发布垂直栅格与渐进式行距(上)发布,已经不知不觉过去了
- 语言:Python IDE:Python.IDE需求 做出彩虹效果颜色空间 RGB模型:光的三原色,共同决定色相 HSB/HSV模型:H色彩
- 一 multiprocessing模块介绍python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu\_cou
- memcached是一套分布式的高速缓存系统,由LiveJournal的Brad Fitzpatrick开发,但被许多网站使用。这是一套开放
- 今晚开放ecmall商城的QQ登陆功能,在回调时产生错误,file_get_contents函数执行时,没有抓取到正确的信息,于是改用cur
- 前言本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。闲来无事听听歌,听
- 从今天起,我将陆续将 ppk on JavaScript 的读书心得发布到这个blog上。ppk是我所景仰的一位web开发者,原因无它,只是
- 问题你想创建一个内嵌变量的字符串,变量被它的值所表示的字符串替换掉。解决方案Python并没有对在字符串中简单替换变量值提供直接的支持。 但
- 目录前言示例文件文件编码空值日期错误函数映射方法1:直接使用labmda表达式方法二:使用自定义函数方法三:使用数值字典映射总结前言本文是给
- 在开发数据库应用中,经常会遇到处理时间的问题,如查询指定时间的记录等。下面就这些常见的问题,结合自己的一些经验,和大家探讨一下这类问题。首先
- 前言今天小编带领大家用Python自制一个自动生成探索性数据分析报告这样的一个工具,大家只需要在浏览器中输入url便可以轻松的访问,如下所示
- 我们小组讨论的话题是tab(标签)在使用时的禁忌。在讨论的开始,大家很快产生了六个感兴趣的话题:如何处理海量的tab?在浏览器中关掉tab之
- 相信在使用MSSQL数据库下使用事务回滚方式操作多表记录的时候,会经常出现“不能在手动或分布事务方式下创建新的连接”的出错提示信息,这个问题
- 三角形是个好东西,比如知道三条边边长,可以判断能不能组成三角形(两边之和大于第三边),如果可以就进一步计算其面积(海伦公式),最后还能把这个
- 本文实例为大家分享了python os模块在系统管理中的应用代码,供大家参考,具体内容如下#临时文件import tempfile temp
- 一、requests库requests是使用Apache2 licensed 许可证的HTTP库。比urllib模块更简洁。Request支