2016-05-25 90 views
0

我用下面的代碼返回一堆元組。返回的值涉及來自多個不同模型的數據。我想知道如何序列化數據並最終以JSON格式返回。如何將下面的Django視圖轉換爲使用Django Rest Framework返回JSON?

def Stream(request): 
    questions = Question.objects.all() 
    answers = Answer.objects.filter(hearts__gte=1) 
    combined = sorted(chain(questions, answers), key=attrgetter('created'), reverse=True) 
    queryset = [] 
    for item in combined: 
     if hasattr(item, 'parent'): 
      try: 
       qs_heart = AnswerHeart.objects.get(answer=item, user=request.user) 
       if qs_heart: 
        hearted = True 
      except AnswerHeart.DoesNotExist: 
       hearted = False 
      try: 
       qs_flag = AnswerFlag.objects.get(answer=item, user=request.user) 
       if qs_flag: 
        flagged = True 
      except AnswerFlag.DoesNotExist: 
       flagged = False 
      queryset.append((item, hearted, flagged)) 
     else: 
      try: 
       qs_heart = QuestionHeart.objects.get(question=item, user=request.user) 
       if qs_heart: 
        hearted = True 
      except QuestionHeart.DoesNotExist: 
       hearted = False 
      try: 
       qs_flag = QuestionFlag.objects.get(question=item, user=request.user) 
       if qs_flag: 
        flagged = True 
      except QuestionFlag.DoesNotExist: 
       flagged = False 
      queryset.append((item, hearted, flagged)) 
    comments = QuestionComment.objects.all() 
    return render(request, "alpha/stream.html", {'queryset': queryset, 'comments': comments}) 
+0

到目前爲止,我一直使用'泛型'爲特定的模型,並且運行良好。至於我不知道在哪裏或如何開始,我還沒有嘗試過這段代碼。 – MiniGunnR

回答

0

難道你不能這樣做嗎?

class MyThingSerializer(serializers.Serializer): 
    my_thing_email = serializers.EmailField() 

def my_view(request): 
    serializer = MyThingSerializer(my_things, many=True) 

    return HttpResponse(JSONRenderer().render(serializer.data), content_type='application/json') 
相關問題