Search code examples
djangotastypie

get related objects in django-tastypie using obj.modelname_set.all()


I am trying to create an api using django tastypie. in my project I have two models Question and Answers. The Answers model has the foreign key to question model. In my api.py I have two resources QuestionResource and AnswerResource.

What i want to do is that when i retrieve a question instance using api call i want to retrieve the related answers instance also. I tried this using adding a key in bundle.data dict and implement it in alter_detail_data_to_serialize. bt what i get as response is a list of objects not the serialized json object. what I got is

and my Code is

 class QuestionResource(ModelResource):
    answer=fields.ToManyField('quiz.api.AnswerResource', 'answer', null=True, full=True)
    topic=fields.ForeignKey(TopicResource,'topic')
    difficulty=fields.ForeignKey(DifficultyLevelResource, 'difficulty')
    class Meta:
        queryset = Question.objects.all()
        resource_name = 'question'
        authorization = Authorization()
        serializer = PrettyJSONSerializer()
        detail_allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
        always_return_data = True
        filtering={'id':ALL,
                'answer':ALL_WITH_RELATIONS
    }

def alter_detail_data_to_serialize(self, request, data):

    data.data['answers']=[obj for obj in data.obj.answer_set.all()]
    return data

def dehydrate(self,bundle):
    bundle.data['related']=bundle.obj.answer_set.all()
    return bundle

class AnswerResource(ModelResource):
    question=fields.ToOneField('quiz.api.QuestionResource', 'answer', null=True,full=True)
    class Meta:
        queryset = Answer.objects.all()
        resource_name = 'answer'
        authorization = Authorization()
        serializer = PrettyJSONSerializer()
        detail_allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
        always_return_data = True
        filtering={
                'question':ALL_WITH_RELATIONS

    }

Solution

  • It was simple, as per the api documentation i had to pass an attirbute to the related field.

     class QuestionResource(ModelResource):
        answer=fields.ToManyField('quiz.api.AnswerResource', 'answer_set', null=True, full=True)
    
    class AnswerResource(ModelResource):
        question=fields.ToOneField('quiz.api.QuestionResource', 'question', null=True)
    

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