0

everyone!

I'm new to Django (and Tastypie) and i'm having some issues with hierarchical data. In my project, we have a couple of categories, represented by the following model:

class Category(MPPTModel):
     desc = models.CharField(max_length=200)
     parent = TreeForeignKey('self', null=True, related_name='children')

As for the server response, i'd like something similar (a json containing all categories and their respective subcategories, and so on):

[     
{
    "id" : 0,
    "decription" : "category1",
    "categories" : [
                      {
                        "id" : 1,
                        "description" : "category2",
                        "categories" : [ ... ]
                       },
                       ...
                    ]
  },
 ...
 ]

The ResourceModel:

class CategoryResource(ModelResource):
    resource_name = 'listCategories'
    queryset = Category.objects.filter.all()

    def alter_list_data_to_serialize(self, request, data):
        return { 'status' : 'success', 'categories' : data }

I've tried subclassing Paginator, but I noticed that I'm only allowed to send plain data inside the 'objects' list. Is there any way to modify this behavior? Am I overseeing something in here?

Thanks for your time.

Erick Luis
  • 11
  • 2

1 Answers1

1

Similar to what silvio mentioned in his reply, i found out that the right way to provide self relationship is by using ToOneField:

class Category(MPTTModel):
    descr = models.CharField(max_length=200)
    parent = TreeForeignField('self', null=True, related_name='children')

class CategoryResource(ModelResource):
    category = fields.ToOneField('self', 'parent', full=True, null=True)

    # Rest of your Resource class

I hope this answer is useful for other people!

Erick Luis
  • 11
  • 2
  • It helped me! :). Also use fields.ToManyField('self', 'children', full=True, null=True) if you want the parent at root followed by children in your response. – Deepak Oct 05 '17 at 16:06