简体   繁体   中英

Django - How to get all related objects in ManyToMany relation

I have a Task model with self referencing.
Every task can have multiple tasks as precondition tasks.

class Task(models.Model):
    title = models.CharField(max_length=64)
    precondition_tasks = models.ManyToManyField(to='self', symmetrical=False)

I need a query to get all related tasks.
eg:
a is pre_task of b
and b is pre_task of c
I want if I get a, I also receive b and c
because a is pre_task of b, and also b is pre_task of c.

I can do this by for loop and a recursive function. But i know this is terrible.
I need to do this and get all related objects by query, not for loop or something like that in Python.

I used to solve same problem with raw sql

from django.db.models import RawSQL
task_id = 2

recursive_cte = """
WITH RECURSIVE cte AS (
    SELECT id, title, ARRAY[id] AS path
    FROM task
    WHERE id = %s

    UNION ALL

    SELECT t.id, t.title, cte.path || t.id
    FROM task t
    JOIN cte ON cte.id = t.precondition_tasks_id
)
SELECT * FROM cte;

"""

related_tasks = Task.objects.raw(recursive_cte, [task_id])

To deal your problem in serializer if for api here are some helpful answers too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM