0

我看到关于 Django 序列化的 SO 有几个问题,但我有额外的复杂性,因为我的字段被翻译(使用django-hvad)。

我有什么工作,但我认为它的效率非常低,而且由于我是 Django 的新手,我想知道是否有更好的方法。

我现在正在做的是获取我需要的三个模型(Survey、SurveyQuestion、SurveyAnswer)中的每一个,分别序列化每个模型,然后在转换为 JSON 之前将它们编织在一起。

这样做的效果是有效的,如 django shell 中所示:

>>> qs = models.SurveyQuestion.objects.language('en').all().filter(survey=1)
>>> for q in qs:
...   res.append({'question': q, 'answers' : models.SurveyAnswer.objects.language('en').all().filter(question=q.pk)})
...
>>> res = []
>>> res
[{'question': <SurveyQuestion: Who is the best Beatle?>, 'answers': [<SurveyAnswer: Paul McCartney>, <SurveyAnswer: George Harrison>, <SurveyAnswer: Ringo Starr>]}, {'question': <SurveyQuestion: Which album from The Beatles was the best?>, 'answers': [<SurveyAnswer: Yellow Submarine>, <SurveyAnswer: Revolver>, <SurveyAnswer: The White Album>]}]

这是相关的代码。如果您需要查看更多信息,请告诉我:

视图.py

class SurveyDetail(APIView):
    """
    Retrieve, update or delete a survey instance.
    """
    def get_object(self, pk):
        try:
            user_language = self.request.GET.get('language')
            return models.Survey.objects.language(user_language).get(pk=pk)
        except models.Survey.DoesNotExist:
            return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    def get_related_questions(self, pk):
        try:
            user_language = self.request.GET.get('language')
            return models.SurveyQuestion.objects.language(user_language).all().filter(survey=pk)
        except models.SurveyAnswer.DoesNotExist:
            return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    def get_related_answers(self, pk):
        try:
            user_language = self.request.GET.get('language')
            return models.SurveyAnswer.objects.language(user_language).all().filter(question=pk)
        except models.SurveyAnswer.DoesNotExist:
            return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    def get(self, request, pk, format=None):
        survey = self.get_object(pk)
        questions = self.get_related_questions(pk)
        res = []
        for q in questions:
            res.append({
                'question': SurveyQuestionSerializer(q).data,
                'answers' : SurveyAnswerSerializer(self.get_related_answers(q.pk), many=True).data
                })
        resp_obj = {
            'survey' : SurveySerializer(survey).data,
            'data' : res
            }

        return JSONResponse(resp_obj)

    def put(self, request, pk, format=None):
        survey = self.get_object(pk)
        serializer = SurveySerializer(survey, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        survey = self.get_object(pk)
        survey.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

序列化程序.py

class SurveySerializer(TranslatableModelSerializer):
    class Meta:
        model = models.Survey
        fields = ['pk', 'title', 'description', 'slug']


class SurveyQuestionSerializer(TranslatableModelSerializer):
    # survey = SurveySerializer(required=False)
    class Meta:
        model = models.SurveyQuestion
        fields = ['pk', 'title', 'content', 'slug', 'survey', 'is_multi_select', 'has_other_field', 'required']


class SurveyAnswerSerializer(TranslatableModelSerializer):
    # question = SurveyQuestionSerializer(required=False)
    class Meta:
        model = models.SurveyAnswer
        fields = ['pk', 'title', 'slug', 'question']
4

1 回答 1

0

我自己想通了。显然,这与未翻译的模型没有什么不同,只是我以前没有。

以下是正确工作的正确代码。请注意每个序列化程序的顺序以及反向外键字段作为序列化程序的包含。

序列化程序.py

class SurveyAnswerSerializer(TranslatableModelSerializer):
    class Meta:
        model = models.SurveyAnswer
        fields = ['pk', 'title', 'slug', 'question']

class SurveyQuestionSerializer(TranslatableModelSerializer):
    answers = SurveyAnswerSerializer(many=True)

    class Meta:
        model = models.SurveyQuestion
        fields = ['pk', 'title', 'content', 'slug', 'survey', 'is_multi_select', 'type', 'scale_min','scale_max', 'has_other_field', 'required', 'answers']

class SurveySerializer(TranslatableModelSerializer):
    questions = SurveyQuestionSerializer(many=True)

    class Meta:
        model = models.Survey
        fields = ['pk', 'title', 'description', 'slug', 'questions']

视图.py

class SurveyDetail(APIView):
    ...
    def get(self, request, pk, format=None):
        survey = self.get_object(pk)
        serializer = SurveySerializer(survey)
        return JSONResponse(serializer.data)

编辑:

事实证明这并不完全有效。在这种情况下,Survey对象被正确翻译,但外键引用的对象,如SurveyQuestionand SurveyAnswer,没有被翻译。这意味着您将获得已翻译和未翻译的混合结果。

于 2016-03-07T21:02:09.367 回答