使用obj.modelname_set.all()获取django-tastypie中的相关对象

Sar*_*mad 0 django tastypie

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

    }
Run Code Online (Sandbox Code Playgroud)

Jam*_*esO 6

您可以在问题模型中添加属性以获得答案,例如

def get_answer(self):
    ... return the correct answer
Run Code Online (Sandbox Code Playgroud)

然后在QuestionResource中使用:

answer = fields.CharField(attribute='get_answer', readonly=True)
Run Code Online (Sandbox Code Playgroud)