我看到关于Django的序列化已经有了several questions,但由于我的字段已被翻译(使用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>]}]
这是相关代码。如果您需要了解更多内容,请与我们联系:
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)
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']
答案 0 :(得分:0)
我自己想通了。显然,它与未翻译的模型没有什么不同,我之前没有做过。
以下是正确运行的更正代码。请注意每个序列化程序的顺序以及反向外键字段作为序列化程序的包含。
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']
class SurveyDetail(APIView):
...
def get(self, request, pk, format=None):
survey = self.get_object(pk)
serializer = SurveySerializer(survey)
return JSONResponse(serializer.data)
结果证明这并不完全有效。在这种情况下,Survey
对象被正确翻译,但外键引用的对象(如SurveyQuestion
和SurveyAnswer
)未被翻译。这意味着您可以获得翻译和未翻译结果的混合。