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

时间:2015-01-23 14:06:41

标签: python django many-to-many

我与我的模特有多对多的关系:

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

如果没有is_root_task()任务是sub_task的依赖项,我希望self返回true。如果我提供root,我想检查与上面相同,但不包括命名的根。

目前的代码只给我错误:

  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

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

1 个答案:

答案 0 :(得分:0)

我设法让这个工作:

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()