Recursive QuerySet with django

若如初见. 提交于 2019-12-06 16:46:58

Shouldn't this work for you?

parts = PartCategory.objects.raw('''
    WITH RECURSIVE
    under_partcategory(id,name, parent_id,level) AS (
    select   api_partcategory.id,api_partcategory.name,api_partcategory.parent_id,0 from api_partcategory where api_partcategory.id=64
    UNION ALL
    SELECT api_partcategory.id,api_partcategory.name,api_partcategory.parent_id, under_partcategory.level+1
    FROM api_partcategory JOIN under_partcategory ON api_partcategory.parent_id=under_partcategory.id
    ORDER BY 2
  )
SELECT * FROM under_partcategory;
''')

You can also look at https://github.com/django-mptt/django-mptt

I had the same problem, and wanted to avoid raw SQL. While I'm on PostgreSQL, this is for a package that may be used under other DB contexts. I found this:

https://django-mptt.readthedocs.io/en/latest/overview.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!