2012-10-09 50 views
14

我對tastypie仍然很陌生,但它看起來像一個非常整潔的庫。不幸的是,我遇到了一些困難。如何使用TastyPie中的外鍵創建新資源

我有兩個型號,以及與這些模型相關的兩個資源:

class Container(models.Model): 
    pass 

class ContainerItem(models.Model): 
    blog = models.ForeignKey('Container', related_name='items') 

# For testing purposes only 
class ContainerResource(ModelResource): 
    class Meta: 
     queryset = Container.objects.all() 
     authorization = Authorization() 

class ContainerItemResource(ModelResource): 
    class Meta: 
     queryset = ContainerItem.objects.all() 
     authorization = Authorization() 

我已通過jQuery創建一個Container對象:

var data = JSON.stringify({}); 

$.ajax({ 
    url: 'http://localhost:8000/api/v1/container/', 
    type: 'POST', 
    contentType: 'application/json', 
    data: data, 
    dataType: 'json', 
    processData: false 
}); 

然而,當我去創造一個ContainerItem,我得到這個錯誤:

container_id may not be NULL 

所以我的問題是:如何在有外鍵關係時創建新資源?

回答

18

ForeignKey關係不在ModelResource上自動錶示。你必須註明:

blog = tastypie.fields.ForeignKey(ContainerResource, 'blog') 

ContainerItemResource,然後當你張貼的容器項目,你可以發佈容器的資源URI。

var containeritemData = {"blog": "/api/v1/container/1/"} 
$.ajax({ 
    url: 'http://localhost:8000/api/v1/containeritem/', 
    type: 'POST', 
    contentType: 'application/json', 
    data: containeritemData, 
    dataType: 'json', 
    processData: false 
}); 

欲瞭解更多信息,請查看以下鏈接:

在本節中,有關於如何創建基礎資源的例子。朝下方,他們提到關係字段不會自動通過內省創建:

http://django-tastypie.readthedocs.org/en/latest/tutorial.html#creating-resources

他們在這裏添加創建關係領域的例子:

http://django-tastypie.readthedocs.org/en/latest/tutorial.html#creating-more-resources

這是一個關於Blurb的加入反向關係:

http://django-tastypie.readthedocs.org/en/latest/resources.html#reverse-relationships

所有the docs都很好,如果你像小說一樣閱讀它們,但很難從中找到具體的東西。

+0

嗨dokkaebi。這看起來像解決方案,但我可以在哪裏閱讀更多內容? – NT3RP

+0

@ NT3RP編輯添加一些文檔鏈接。 – dokkaebi

+0

我知道這個答案很老,我的問題有點偏離主題,但是tastypie也有一些東西,當你獲取一個資源並且你有一個外鍵,而不是外部資源的URL,你會得到實際的對象? –