0

我正在尝试使用 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

    }
4

2 回答 2

6

您可以向您的问题模型添加一个属性以获得答案,例如

def get_answer(self):
    ... return the correct answer

然后在 QuestionResource 中使用:

answer = fields.CharField(attribute='get_answer', readonly=True)
于 2013-07-30T09:48:28.430 回答
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

于 2013-11-29T08:32:03.393 回答