Search code examples
pythondjangotastypie

Django Tastypie throws a 'maximum recursion depth exceeded' when full=True on reverse relation.


I get a maximum recursion depth exceeded if a run the code below:

from tastypie import fields, utils
from tastypie.resources import ModelResource
from core.models import Project, Client


class ClientResource(ModelResource):
    projects = fields.ToManyField(
        'api.resources.ProjectResource', 'project_set', full=True
    )
    class Meta:
        queryset = Client.objects.all()
        resource_name = 'client'


class ProjectResource(ModelResource):
    client = fields.ForeignKey(ClientResource, 'client', full=True)
    class Meta:
        queryset = Project.objects.all()
        resource_name = 'project'

# curl http://localhost:8000/api/client/?format=json
# or
# curl http://localhost:8000/api/project/?format=json

If a set full=False on one of the relations it works. I do understand why this is happening but I need both relations to bring data, not just the "resource_uri". Is there a Tastypie way to do it? I managed to solve the problem creating a serialization method on my Project Model, but it is far from elegant. Thanks.


Solution

  • You would have to override full_dehydrate method on at least one resource to skip dehydrating related resource that is causing the recursion.

    Alternatively you can define two types of resources that use the same model one with full=Trueand another with full=False.