停止在 tastypie 中重复相关对象

Stop repeating related objects in tastypie

嘿,我是 django tastypie 的新手,我需要帮助解决我的数据重复问题 我有这个模型用于我的待办事项任务和子任务。

class Todo(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    creation_date = models.DateField(auto_now=True)
    due_date = models.DateField(blank=True, null=True)
    completed = models.BooleanField(default=False)
    parent_task = models.ForeignKey('self', related_name='subtask', 
    blank=True, null=True)

到目前为止我已经得到了这个资源。

class TodoResource(ModelResource):
    subtask = fields.ToManyField(
        "todos.api.SubtakResource", 'subtask',
        related_name='subtask', full=True,
        null=True, blank=True
    )

    class Meta:
        queryset = Todo.objects.all()
        resource_name = 'todo'
        authorization = Authorization()


class SubtakResource(ModelResource):
   parent = fields.ForeignKey(
        "todo.api.TodoResource", 'parent',
        use_in='detail', null=True, blank=True
   )

   class Meta:
       queryset = Todo.objects.all()

这是我得到的结果

 {
"meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 2
},
"objects": [{
    "completed": false,
    "creation_date": "2018-07-01",
    "description": "Have Fun muoy booy",
    "due_date": "2018-07-05",
    "id": 7,
    "resource_uri": "/api/todo/7/",
    "subtask": [{
        "completed": false,
        "creation_date": "2018-07-01",
        "description": "Bira",
        "due_date": "2018-07-06",
        "id": 8,
        "parent": null,
        "resource_uri": "",
        "title": "Drink beer"
    }],
    "title": "Have Fun"
},
{
    "completed": false,
    "creation_date": "2018-07-01",
    "description": "Bira",
    "due_date": "2018-07-06",
    "id": 8,
    "resource_uri": "/api/todo/8/",
    "subtask": [

    ],
    "title": "Drink beer"
}

] }

与父结果相关的最后一个结果出现了两次,我该如何停止,请帮忙。 resouce_uri 字段也即将 null

不知道Tastypie也支持自引用关系。如果您假设我们向 Note 模型添加了适当的自引用外键,那么在 Tastypie 中实现类似的关系将如下所示:

# myapp/api/resources.py
from tastypie import fields
from tastypie.resources import ModelResource
from myapp.models import Note


class NoteResource(ModelResource):
    sub_notes = fields.ToManyField('self', 'notes')

    class Meta:
        queryset = Note.objects.all()

文档:http://django-tastypie.readthedocs.io/en/latest/resources.html#reverse-relationships