停止重复美味中的相关对象

时间:2018-07-01 19:20:36

标签: python django django-rest-framework 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

1 个答案:

答案 0 :(得分:0)

不知道Tastypie也支持自我参照关系。如果您假设我们在Note模型中添加了适当的自引用ForeignKey,则在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()

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