2012-10-09 52 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,你会得到实际的对象? –