Search code examples
pythondjangoapiresttastypie

How to declare child resources in Tastypie?


I have this models.py:

from django.db import models

class Item(models.Model):
    text = models.TextField()

class Note(models.Model):
    text = models.TextField()
    items = models.ManyToManyField(Item)

And this api.py:

import tastypie
from tastypie.resources import ModelResource
from tastypie.api import Api
from main.models import Item, Note

class ItemResource(ModelResource):
    class Meta:
        resource_name = 'items'
        queryset = Item.objects.all()

class NoteResource(ModelResource):
    items = tastypie.fields.ToManyField(ItemResource, 'items', full=True)

    class Meta:
        resource_name = 'notes'
        queryset = Note.objects.all()

api = Api(api_name='v1')
api.register(NoteResource())

I want the only endpoint to items be:

/api/v1/notes/4/items

/api/v1/notes/4/items/2

And no /api/v1/items/?note=4

I've been reading Tastypie documentation and i didn't found any info on this.

This document recommends the URL form i post here.

How can i accomplish this?


Solution

  • Using Django REST Framework (posterity, see comments on OP), child resources are declared as follows (simple example):

    class AddressSerializer(ModelSerializer):
        """
        A serializer for ``Address``.
        """
        class Meta(object):
            model = Address
    
    
    class OrderSerializer(ModelSerializer):
        """
        A serializer for ``Order``.
        """
        address = AddressSerializer()
    
        class Meta(object):
            model = Order
    

    To get started, I highly recommend simply following this tutorial. It will get you 100% of what you need, in terms of customizing your URLs, customizing your serialized output, etc.

    Tasty pie is a great project, and the creator, Daniel Lindsley, is a really smart guy (I worked with him for a short while), but just like every other great project, somebody came along and blew our socks off with something new that has learned from the good and bad parts of the existing framework.