Search code examples
pythondjangodjango-rest-frameworktastypie

Stop repeating related objects in tastypie


Hey there I'm new to django tastypie and I need a help where my data is getting repeated I've this model for my todo task and subtask.

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)

And this resource I've came with so far.

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

This is the result I'm getting

 {
"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"
}

] }

The last result which is related to the parent result coming twice how can I stop that please help. Also the resouce_uri field is coming null.


Solution

  • Didn't know that Tastypie also supports self-referential relations. If you assume we added the appropriate self-referential ForeignKey to the Note model, implementing a similar relation in Tastypie would look like:

    # 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