Django-Tastypie 自己 children

Django-Tastypie self children

正在尝试为多个子任务制作 api。 我有任务模型,可以有另一个任务作为 parent:

class Task(models.Model):
    parent_task = models.ForeignKey("Task", null=True, blank=True)
    name = models.CharField(max_length=64)

    def __unicode__ (self):
        return self.name

现在我正在尝试制作 tastypie 资源:

class TaskResource(ModelResource):
    parent_task = fields.ForeignKey(TaskResource, 'parent_task', full=False) <-- ERROR HERE

    class Meta:
        queryset = Task.objects.all()
        resource_name = 'task'
        list_allowed_methods = ['get', 'put', 'post', 'delete']
        include_resource_uri = False

    def dehydrate(self, bundle, for_list=False):
        bundle.data["subtasks"] = "how?" <-- HOW??
        return bundle

感谢您的宝贵时间。

P.S。我需要这样的东西:

[
    {
        "id": 1,
        "name": "Task 1",
        "subtasks": [
            {
                "id": 1,
                "name": "Task 1",
                "subtasks": [...]
            }
        ]
    },
    {
        "id": 2,
        "name": "Task 2",
        "subtasks": "how?"
    }
]

几乎是 Including child resources in a Django Tastypie API 的副本,但不完全是。

  1. 所以你的第一个问题是你指定的 relation to self 错误。它应该只是 self:

    parent_task = fields.ForeignKey('self', 'parent_task', null=True, full=False)
    
  2. 其次,注意 null=True - parent 可以是 null.

  3. 最后,您只需要添加另一个关系字段并询问完整的详细信息

    subtasks = fields.ToManyField('self', 'task_set', full=True)
    

    task_setTask.parent_task 字段的 related_name

结果代码是:

class TaskResource(ModelResource):
    parent_task = fields.ForeignKey('self', 'parent_task', null=True, full=False)
    subtasks = fields.ToManyField('self', 'subtasks', full=True)

    class Meta:
        queryset = Task.objects.all()
        resource_name = 'task'
        list_allowed_methods = ['get', 'put', 'post', 'delete']
        include_resource_uri = False

结果:

{
    "meta": {
        "previous": null, 
        "total_count": 3,  
        "offset": 0,  
        "limit": 20, 
        "next": null
    },  
    "objects": [
        {
            "parent_task": null, 
            "subtasks": [
                {
                    "parent_task": "/api/v1/task/1/", 
                    "subtasks": [], 
                    "id": 2,  
                    "name": "Root's Child 1"
                },
                {
                    "parent_task": "/api/v1/task/1/", 
                    "subtasks": [], 
                    "id": 3,  
                    "name": "Root's Child 2"
                }
            ],
            "id": 1,  
            "name": "Root Task"
        },
        {
            "parent_task": "/api/v1/task/1/", 
            "subtasks": [], 
            "id": 2,  
            "name": "Root's Child 1"
        },
        {
            "parent_task": "/api/v1/task/1/", 
            "subtasks": [], 
            "id": 3,  
            "name": "Root's Child 2"
        }
    ]   
}