Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new resource with foreign key in TastyPie

I'm still new to tastypie, but it seems like a really neat library. Unfortunately, I'm having some difficulties with it.

I have two models, and two resources associated with those models:

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

I have created a Container object via jQuery:

var data = JSON.stringify({});

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

However, when I go to create a ContainerItem, I get this error:

container_id may not be NULL

So my question is: How do I create a new resource when there is a ForeignKey relationship?

like image 333
NT3RP Avatar asked Oct 09 '12 16:10

NT3RP


1 Answers

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.

like image 144
dokkaebi Avatar answered Sep 25 '22 11:09

dokkaebi