我正在尝试使用django tastypie创建一个api。在我的项目中,我有两个模型问题和答案。 Answers模型具有问题模型的外键。在我的api.py中,我有两个资源QuestionResource和AnswerResource。
我想要做的是,当我使用api调用检索问题实例时,我也希望检索相关的答案实例。我尝试使用在bundle.data dict中添加一个键并在alter_detail_data_to_serialize中实现它。我得到的是响应是一个对象列表而不是序列化的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
}
答案 0 :(得分:6)
您可以在问题模型中添加属性以获得答案,例如
def get_answer(self):
... return the correct answer
然后在QuestionResource中使用:
answer = fields.CharField(attribute='get_answer', readonly=True)
答案 1 :(得分:0)
很简单,根据api文档,我必须将属性传递给相关字段。
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)
阅读文档http://django-tastypie.readthedocs.org/en/latest/resources.html#reverse-relationships