我正在使用项目管理应用程序。应用程序需要的要点之一是创建具有依赖性的任务的可能性,即任务2依赖于任务1,任务3依赖于任务2和任务B,等等。这将生成DAG(有向无环图)。
问题是如何使用Django默认ORM存储此“图形”。
我提供了一个使用多对多关系(带有自我的任务)和避免创建周期的触发器的解决方案,但是我仍然不知道如何实现一些操作,例如从单个节点获取整个图形。
有没有人知道如何很好地实现它?例如,这将允许执行关键路径方法的实现。
谢谢
让我们创建一个简单的Task
模型:
class Task(models.Model):
name = models.CharField(...)
previous_tasks = models.ManyToMany('Task', ..., related_name='next_tasks')
现在创建taks_a
并task_b
-task_b
取决于task_a
:
# create task_a, task_b:
task_a = Task.objects.create(name='First Task')
task_b = Task.objects.create(name='Second task')
# add task_a as a dependency for task_b:
task_b.previous_tasks.add([task_a])
task_b.save()
现在,我们可以像这样访问这些任务:
# get the tasks to do after task_a is complete:
task_a = Task.objects.get(id='<task-a-id>')
tasks_to_do_after_task_a = task_a.next_tasks.all() # returns a queryset with <task_b>
# get the tasks we need to complete before task_b:
task_b = Task.objects.get(id='<task-b-id>')
tasks_that_task_b_depends_on = task_b.previous_tasks.all() # returns a queryset with <task a>
最后,假设task_a
实际上有一些与其相关的任务:
# iterate over all the tasks that depend on task a:
for tasks in task_a.next_tasks.all():
# do some logic, i.e. find longest task:
...
# filter for a specific next_task on task_a:
some_task = task_a.next_tasks.filter(some_keyword='some_value')
# assume we have a duration time-field on tasks:
next_longest_task = task_a.next_tasks.order_by('-duration')[0] # gets the next task with the longest duration
从那里,您可以根据需要实施寻路逻辑/其他算法。
好的-使用上述结构,我们可以定义如下函数:
def get_task_list(task):
# get the next_tasks queryset, it will either contain tasks or be an empty queryset:
next_tasks = task.next_tasks.all()
# check if the current task has any children:
if next_tasks:
# do some logic, check for longest tasks / add next tasks to a list
...
# pass each next task back into the function:
for next_task in next_tasks:
return get_task_list(next_task)
# exit if there are no more next tasks:
else:
# do some logic on exiting, calculate the time to complete all tasks:
...
return <optional-content>
您可以对递归函数进行更多研究,但这应该可以帮助您入门。您可以聪明地查看函数中的上一个任务或下一个任务。您也可以将此作为方法添加到Task
模型中,以便可以在任务实例上调用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句