【问题标题】:Stop repeating related objects in tastypie停止在美味派中重复相关对象
【发布时间】:2018-12-10 02:22:23
【问题描述】:

嘿,我是 django sweetpie 的新手,在我的数据重复的地方我需要帮助 我的 todo 任务和子任务有这个模型。

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

【问题讨论】:

    标签: python django django-rest-framework tastypie


    【解决方案1】:

    不知道 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()
    

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

    【讨论】:

    • 您能否提供您实施的解决方案以解决 ToDo API 上的自引用关系?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 2015-11-04
    • 2014-02-21
    • 2012-10-30
    • 2014-01-23
    • 1970-01-01
    相关资源
    最近更新 更多