我正在尝试使用 django sweetpie 创建一个 api。在我的项目中,我有两个模型问题和答案。Answers 模型具有问题模型的外键。在我的 api.py 中,我有两个资源 QuestionResource 和 AnswerResource。
我想要做的是,当我使用 api 调用检索问题实例时,我也想检索相关的答案实例。我尝试使用在 bundle.data 字典中添加一个键并在 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
}