django 一个表中包括id和parentid,如何通过parentid找到全部父爷id

在Django中,如果你想要通过parentid找到一个记录的所有祖先(父祖)记录的id,你可以通过递归查询来实现。在Django中,你可以使用Django的Treebeard库来处理树形结构的数据,例如MPTT(Modified Preorder Tree Traversal)。但是,如果你不想使用第三方库或者你的需求比较简单,你可以通过编写递归查询函数来实现。

这里有两种常见的方法来实现:

方法1:使用Django的QuerySet的annotate和Subquery

这种方法适用于Django 2.0及以上版本。

from django.db.models import Subquery, OuterRef, IntegerField

def get_all_ancestors_ids(instance):

首先找到所有祖先的id

ancestors_ids = YourModel.objects.filter(

id=OuterRef('parentid')

).values('id')

复制代码
# 通过Subquery获取所有祖先的id
all_ancestors_ids = YourModel.objects.filter(
    id=instance.id
).annotate(
    all_ancestors_ids=Subquery(
        ancestors_ids.values('id')[:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id'][:'id']  # 这里理论上应该有无限层级的递归查询,但实际上你需要根据实际层级来调整,例如最多10层
    )
).values_list('all_ancestors_ids', flat=True)

return list(all_ancestors_ids)

注意:这种方法理论上可以实现无限层级的递归查询,但实际上你需要手动指定层级数(例如上面代码中的层级数仅为示例,你需要根据实际情况调整)。这种方法在层级非常深的情况下可能不实用。

方法2:递归函数查询

对于简单的应用场景,你可以定义一个递归函数来手动查找所有祖先。

def get_all_ancestors(instance):

ancestors = \[\]

current = instance

while current.parentid is not None:

current = YourModel.objects.get(id=current.parentid)

ancestors.append(current.id)

return ancestors::-1 # 返回时反转列表以获得正确的顺序(从祖先到子孙)

使用这个函数,你可以像这样调用它:

instance = YourModel.objects.get(id=some_id)

ancestors = get_all_ancestors(instance)

print(ancestors)

方法3:使用MPTT库(推荐对于复杂树形结构)

如果你需要处理更复杂的树形结构(例如,需要频繁查询祖先节点等),建议使用MPTT库。首先安装MPTT:

pip install django-mptt

然后在你的模型中使用MPTT:

from mptt.models import MPTTModel, TreeForeignKey

from django.db import models

class Category(MPTTModel):

name = models.CharField(max_length=50)

parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

复制代码
def get_ancestors(self, ascending=False, include_self=False):
    ancestors = self.get_cached_ancestors(ascending=ascending, include_self=include_self)
    return [a.id for a in ancestors]  # 获取所有祖先的ID列表

使用:

instance = Category.objects.get(id=some_id)

ancestors_ids = instance.get_ancestors(include_self=False) # 获取所有父祖ID,不包括自身

print(ancestors_ids)

MPTT提供了非常强大的树形结构操作能力,包括但不限于获取祖先、子孙等。如果你预计会有很多复杂的树形操作需求,使用MPTT会是更好的选择。

相关推荐
顾林海3 小时前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱6 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽10 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码11 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱20 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵1 天前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio1 天前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽1 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate