如何在列表视图中获取两个查询集

时间:2019-01-31 11:12:50

标签: django django-models django-rest-framework

我有2个问题模型扩展了基本的Question模型:

class Question(models.Model):
    title = models.CharField(blank=False, max_length=200)
    order = models.PositiveIntegerField(default = 0)
    is_actuve = models.BooleanField(default = False)

class OptionQuestion(Question):
    is_bulletpoint = models.BooleanField(default=False)
    has_others = models.BooleanField(default=False)
    has_context = models.BooleanField(default=False)
    options = ArrayField(models.CharField(max_length=100), verbose_name='گزینه‌ها')


class ItemQuestion(Question):
    pass

我原本的Question抽象类,但我需要所有问题的唯一的ID,而现在我需要对他们俩的ListAPIView的。 我有2个串行为OptionQuestionItemQuestion分别。 我只需要实现这将办理的问题清单的请求的视图,并在适当的串行每个。

处理它们
class QuestionListView(ListAPIView):
    serializer_class_OptionQuestion = OptionQuestionSerializer
    serializer_class_ItemQuestion = ItemQuestionSerializer

    def get_queryset_OptionQuestion(self):
        #???

1 个答案:

答案 0 :(得分:1)

您可以尝试

class QuestionListView(ListAPIView):
   serializer_class_OptionQuestion = OptionQuestionSerializer
   serializer_class_ItemQuestion = ItemQuestionSerializer

   def get(self, request, *args, **kwrgs):
      if request.method == 'GET':
          query1 = Question.objects.all()
          query2 = OptionQuestion.objects.all()

          seralizer1 = self.serializer_class_OptionQuestion(query1)
          seralizer2 = self.serializer_class_ItemQuestion(query2)

          return Response(
             {
               'data1':seralizer1.data,
               'data2':seralizer2.data,
             }
          )

希望它能解决您的问题