Note that there are some explanatory texts on larger screens.

plurals
  1. POget related objects in django-tastypie using obj.modelname_set.all()
    primarykey
    data
    text
    <p>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. </p> <p>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 </p> <p>and my Code is </p> <pre><code> 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 } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload