Sam Hooke

Using a non-pk as a foreign key in a Tastypie endpoint

Situation: using a non-pk for the detail URL in tastypie. Then performing a PATCH to update an item which is a foreign key to a non-pk detail URL gives the following error:

    "my_endpoint": {
        "my_field_to_a_detail_url": [
            "Select a valid choice. That choice is not one of the available choices."

To workaround, create a custom model form:

from import Foo
from django.forms import ModelForm

class FooForm(ModelForm):
    """Form corresponding to Foo model.

    class Meta:
        model = Foo
        fields = '__all__'
        exclude = ['my_field_to_a_detail_url']

Then use that form within your tastypie resource:

from tastypie.resources import Resource
from import Foo
from my_app.forms import FooForm

class FooResource(Resource):
    class Meta:
            queryset, resource_name, authentication,
            authorization, filtering, ordering, validation
        ) = Resource.setupMeta(
            query_model=Foo, resource_name='foo',