2014-01-14 45 views
1

我有這個models.py如何在Tastypie中聲明子資源?

from django.db import models 

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

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

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

我想唯一的端點項目是:

/api/v1/notes/4/items

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

並且沒有/api/v1/items/?note=4

我一直在閱讀Tastypie文檔,並且我沒有在此找到任何信息。

This文檔推薦我在此處發佈的URL表單。

我該如何做到這一點?

+0

你可能想看看http://www.django-rest-framework.org/ – orokusaki

+0

@orokusaki好吧,我一直在閱讀很多。它看起來比Tastypie更好。你能指出我在正確的方向做這個restframework? – sanfilippopablo

+0

我剛剛爲您添加了更多信息的答案。 – orokusaki

回答

1

使用Django REST Framework(後人,看到OP評論),子資源的聲明如下(簡單的例子):

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 

要開始,我強烈建議只是按照this tutorial。它會讓你百分之百滿足你的需求,在定製你的URL,定製你的序列化輸出等方面。

美味的派是一個偉大的項目,而創建者Daniel Lindsley是一個非常聰明的人(我與他一起工作了一段時間),但就像所有其他偉大的項目一樣,有人來到我們的襪子裏,用新的learned from the good and bad parts of the existing framework吹掉了我們的襪子。