[Fixed]-How to create new resource with foreign key in TastyPie

23👍

ForeignKey relationships are not represented automatically on the ModelResource. You’ll have to specify:

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

on the ContainerItemResource, and then you can post the resource uri of the container when you post up the container item.

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
});

For more info, check out these links:

In this section, there is an example of how to create basic resources. Toward the bottom, they mention that relationship fields are not automatically created through introspection:

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

Here they add an example of creating a relationship field:

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

Here is a blurb about adding reverse relations:

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

All the docs are good if you read them like a novel, but it can be hard to find specific things among them.

Leave a comment