如何检查我的 Django 模型实例是否是根?

How can I check if my Django model instance is the root?

我与我的模型之间存在多对多关系:

class Task(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    completed = models.BooleanField(default=False)
    project = models.ForeignKey('Project', related_name="tasks")
    dependency = models.ManyToManyField('self', through='Dependency', null=True, 
        blank=True, through_fields=('task', 'sub_task'), symmetrical=False)

    def sub_tasks(self, **kwargs):
        qs = self.dependency.filter(**kwargs)
        for sub_task in qs:
            qs = qs | sub_task.sub_tasks(**kwargs)
        return qs

    def is_root_task(self, root=None):
        if root:
            # Are their no dependencies where I am the Sub-Task
            return not self.dependency_sub_task.exists()
        else:
            # Are their no dependencies where I am the Sub-Task,
            # except for where the task is my 'parent'
            return not self.dependency_sub_task.exclude(task_id__exact=root.id).exists()

    def __str__(self):
        return self.title

class Dependency(models.Model):
    task = models.ForeignKey(Task, related_name="dependency_task")
    sub_task = models.ForeignKey(Task, related_name="dependency_sub_task")

    def __str__(self):
        return self.task.title+ " depends on "+ self.sub_task.title

如果 self 任务是 sub_task 的依赖项不存在,我希望 is_root_task() 为 return true。如果我提供根,我想检查与上面相同的内容,但不包括命名根。

当前代码只给我这样的错误:

  File "C:\Python34\lib\site-packages\django\db\models\sql\query.py", line 1389, in raise_field_error
    "Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'dependency_task' into field. Choices are: id, sub_task, sub_t
ask_id, task, task_id

这是检查根性的正确方法吗?或者有更好的方法吗?

我设法让它工作:

def is_root_task(self, root=None):
    '''Returns true if the task is the root of a series of other tasks'''
    # all the tasks that have 'task' as their subtask
    super_tasks = self.dependency_sub_task.all()
    if not root:
        # Are their no dependencies where I am the Sub-Task
        return not super_tasks.exists()
    else:
        # Are their no dependencies where I am the Sub-Task,
        # except for where the task is my 'parent'
        return not super_tasks.exclude(task_id__exact=root.id).exists()