如何在TastyPie中使用外键创建新资源

NT3*_*3RP 16 django django-models 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()
Run Code Online (Sandbox Code Playgroud)

Container通过jQuery 创建了一个对象:

var data = JSON.stringify({});

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

但是,当我去创建一个时ContainerItem,我收到此错误:

container_id may not be NULL
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:当存在ForeignKey关系时,如何创建新资源?

dok*_*ebi 21

ForeignKey关系不会在ModelResource上自动表示.你必须指定:

blog = tastypie.fields.ForeignKey(ContainerResource, 'blog')
Run Code Online (Sandbox Code Playgroud)

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
});
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看以下链接:

在本节中,有一个如何创建基本资源的示例.在底部,他们提到关系字段不是通过内省自动创建的:

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

在这里,他们添加了创建关系字段的示例:

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

这是关于添加反向关系的一个模糊:

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

如果你像小说一样阅读它们,那么所有的文档都是好的,但是在它们之间很难找到具体的东西.