Django Tastypie を使用して API を作成しようとしています。私のプロジェクトでは、質問と回答の2つのモデルがあります。Answers モデルには、質問モデルへの外部キーがあります。私のapi.pyには、QuestionResourceとAnswerResourceの2つのリソースがあります。
私がやりたいことは、API呼び出しを使用して質問インスタンスを取得するときに、関連する回答インスタンスも取得したいということです。bundle.data dict にキーを追加してこれを試し、alter_detail_data_to_serialize に実装しました。bt 応答として得られるのは、シリアル化された json オブジェクトではなく、オブジェクトのリストです。私が得たものは
そして私のコードは
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
}