How to recursively query in django efficiently?

前端 未结 2 1913
旧时难觅i
旧时难觅i 2021-01-02 12:54

I have a model, which looks like:

class StaffMember(models.Model):

    id = models.OneToOneField(to=User, unique=True, primary_key=True, related_name=\'staf         


        
2条回答
  •  心在旅途
    2021-01-02 13:21

    If you're using a database that supports recursive common table expressions (e.g. PostgreSQL), this is precisely the use-case.

    team = StaffMember.objects.raw('''
        WITH RECURSIVE team(id, supervisor) AS (
              SELECT id, supervisor 
              FROM staff_member
              WHERE id = 42
            UNION ALL
              SELECT sm.id, sm.supervisor
              FROM staff_member AS sm, team AS t
              WHERE sm.id = t.supervisor
            )
        SELECT * FROM team
    ''')
    

    References: Raw SQL queries in Django
    Recursive Common Table Expressions in PostgreSQL

提交回复
热议问题