我看到关于 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']