def get(self, request, format=None): try: position_type_name = 'Practice' position_type = TalentPositionType.objects.get( name=position_type_name) questions = Question.objects.filter( talent_position_type=position_type.id).order_by('created') except TalentPositionType.DoesNotExist: raise Http404 if len(questions) > 5: # generate random numbers # randnums = random.sample(range(len(questions)), 5) # create new question list with the random numbers static_questions = [] for index in range(0, 5): print('=== index: ', index) static_questions.append(questions[index]) serializer = QuestionSerializer(static_questions, many=True) return Response(serializer.data) else: serializer = QuestionSerializer(questions, many=True) return Response(serializer.data)
def put(self, request): queryset = Question.objects.get(id = request.data['id']) serializer = QuestionSerializer(queryset, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)
def get(self, request, format=None): try: position_type = request.query_params.get('position_type') #request.query_params.get('position_type') position_sub_type = request.query_params.get('position_sub_type') #request.query_params.get('position_type') if not position_type: questions = Question.objects.all() else : position_type = TalentPositionType.objects.get(name__iexact=position_type) if not position_sub_type: print('===== filter question: ', position_type.id) questions = Question.objects.filter(talent_position_type=position_type.id) else: questions = Question.objects.filter(talent_position_type=position_type.id).filter(talent_position_sub_type=position_sub_type) except TalentPositionType.DoesNotExist: raise Http404 if len(questions) > 5: # generate random numbers randnums = random.sample(range(len(questions)), 5) # create new question list with the random numbers random_questions = [] for index in randnums: random_questions.append(questions[index]) serializer = QuestionSerializer(random_questions, many=True) return Response(serializer.data) else : serializer = QuestionSerializer(questions, many=True) return Response(serializer.data)
def post(self, request): serializer = QuestionSerializer(data=request.data) try: if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)
def question_list_or_post(request): """List all Questions or create a new one.""" if request.method == 'GET': questions = Question.objects.all() serializer = QuestionSerializer(questions, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = QuestionSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=Profile.objects.get(user=request.user)) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_get_single_question(self): """Test to view single question""" question = staged_question(user=self.user) url = question_detail_url(question.id) response = self.client.get(url) serializer = QuestionSerializer(question) self.assertEqual(response.data, serializer.data)
class SurveySerializer(ModelSerializer): # TODO: Add field for layout questions = QuestionSerializer(many=True) layout = SerializerMethodField() class Meta: model = Survey fields = '__all__' def get_layout(self, obj): layouts = obj.survey_question_set.select_related() return [layout.get_layout_display() for layout in layouts] def create(self, validated_data): validated_data.pop('questions') clients_data = validated_data.pop('clients', []) survey = Survey.objects.create(**validated_data) data = self.get_initial() questions = data.get('questions') for client in clients_data: survey.clients.add(client) for question in questions: question_instance = Question.objects.get(pk=question.get('id')) survey.survey_question_set.create(survey=survey, layout=data.get('layout'), question=question_instance) return survey
class GroupDetailSerializer(serializers.ModelSerializer): question = QuestionSerializer(many=True) class Meta: model = Group fields = ['name', 'number', 'question']
def ops_view_all(self): # related_obj_type = self.request.GET.get("related_obj_type", None) # related_obj_id = self.request.GET.get("related_obj_id", None) # if related_obj_type is None or related_obj_id is None: # return ErrorCode.INVALID_INPUT, None smfrqs = SM.objects.filter_active( related_obj_type=self.related_obj_type, related_obj_id=self.related_obj_id, escape_task_id=self.task_id ) if not smfrqs.exists(): return ErrorCode.SURVEY_MODEL_SUBSTANDARD_NOT_RELATED_QUESTION, None facet_infos = [] related_facet_ids = [] for smfr in smfrqs: facet_ids, facet_weights = smfr.get_facet_infos() for index, facet_id in enumerate(facet_ids): if facet_id not in related_facet_ids: facet_infos.append({ "id": facet_id, "weight": facet_weights[index], "name": QuestionFacet.objects.get(id=facet_id).name }) related_facet_ids.append(facet_id) question_ids = SQ.objects.filter_active( # survey_id=self.survey_id, model_facet_relation_id__in=smfrqs.values_list("id", flat=True), model_facet_relation_id__in=smfrqs.values_list("id", flat=True), escape_task_id=self.task_id ).values_list("question_id", flat=True) questions = Question.objects.filter_active(id__in=question_ids) question_data = QuestionSerializer(instance=questions, many=True).data return ErrorCode.SUCCESS, {"facet_infos": facet_infos, "question_data": question_data}
def ops_view_all(self): smfrqs = SurveyModelFacetRelation.objects.filter_active( survey_id=self.survey_id, related_obj_type=self.related_obj_type, related_obj_id=self.related_obj_id, related_facet_type=SurveyModelFacetRelation.RELATED_FACET_TYPE_OPTION ) if not smfrqs.exists(): return ErrorCode.SURVEY_MODEL_SUBSTANDARD_NOT_RELATED_QUESTION, None facet_infos = [] related_facet_ids = [] for smfr in smfrqs: facet_ids, facet_weights = smfr.get_facet_infos() for index, facet_id in enumerate(facet_ids): if facet_id not in related_facet_ids: facet_infos.append({ "id": facet_id, "weight": facet_weights[index], "name": QuestionFacet.objects.get(id=facet_id).name }) related_facet_ids.append(facet_id) # 这边的返回question要不要返回 question_ids_qs = SurveyQuestionRelation.objects.filter_active( survey_id=self.survey_id, model_facet_relation_id__in=smfrqs.values_list("id", flat=True) ) question_ids = question_ids_qs.filter(related_facet_type=SurveyQuestionRelation.RELATED_FACET_TYPE_QUESTION).values_list("question_id", flat=True) questions = Question.objects.filter_active(id__in=question_ids) question_data = QuestionSerializer(instance=questions, many=True).data options_ids = question_ids_qs.filter(related_facet_type=SurveyQuestionRelation.RELATED_FACET_TYPE_OPTION).values_list("question_option_id", flat=True) options = QuestionOption.objects.filter_active(id__in=options_ids) option_data = QuestionOptionSerializer(instance=options, many=True).data return ErrorCode.SUCCESS, {"facet_infos": facet_infos, "question_data": question_data, "option_data": option_data}
def test_get_question_list(self): """Test to get question list, no auth""" response = self.client.get(QUESTION_LIST_URL) questions = Question.objects.all().order_by('-id') serializer = QuestionSerializer(questions, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data)
class QuestionnairePartialSerializer(ModelSerializer): id = serializers.UUIDField(read_only=True) variables = VariablePartialSerializer(many=True, read_only=True) questions = QuestionSerializer(many=True, read_only=True) class Meta: model = Questionnaire fields = '__all__'
class VariableSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) questions = QuestionSerializer(many=True, read_only=True) answers = AnswerSerializer(many=True, read_only=True) class Meta: model = models.Variable fields = '__all__'
def ops_view_praise(self): smfrqs = SurveyModelFacetRelation.objects.filter_active( survey_id=self.survey_id, related_obj_type=self.related_obj_type, related_obj_id=self.related_obj_id) if not smfrqs.exists(): return ErrorCode.SURVEY_MODEL_SUBSTANDARD_NOT_RELATED_QUESTION, None question_ids = SurveyQuestionRelation.objects.filter_active( survey_id=self.survey_id, model_facet_relation_id__in=smfrqs.values_list("id", flat=True)).values_list( "question_id", flat=True) questions = Question.objects.filter_active(id__in=question_ids, question_category=Question.CATEGORY_PRAISE) question_data = QuestionSerializer(instance=questions, many=True).data return ErrorCode.SUCCESS, {"question_data": question_data}
def question_get_edit_delete(request, pk): """Get, Edit or Delete specific Question if you are an owner.""" try: question = Question.objects.get(pk=pk) except Question.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = QuestionSerializer(question) return Response(serializer.data) if request.method == 'PUT': serializer = QuestionSerializer(question, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': question.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def get(self, request, format=None, **kwargs): """ Return a list of all blogs or questions or both. """ type_ = self.request.query_params.get('type', None) tag_name = self.request.query_params.get('tag_name', None) # Tagged item type specified if type_ != None and tag_name != None: target_type = ContentType.objects.get( app_label=type_, model=type_) items = target_type.model_class().objects.filter( tags__tag_name__contains=tag_name) if type_ == "blog": return Response([BlogSerializer(blog).data for blog in items]) elif type_ == "question": return Response([QuestionSerializer(question).data for question in items]) else: return Response("Unknow tagged item type", status=status.HTTP_400_BAD_REQUEST) # Tagged item type specified, return all elif type_ == None and tag_name != None: blogs = Blog.objects.filter(tags__tag_name__contains=tag_name) data = {"blogs": [BlogSerializer(blog).data for blog in blogs]} questions = Question.objects.filter(tags__tag_name__contains=tag_name) data.update({"questions": [QuestionSerializer(question).data for question in questions]}) return Response(data) # invalid parameters elif type_ != None and tag_name == None: return Response("tag name is not provided", status=status.HTTP_400_BAD_REQUEST) else: return Response("no query parameter is provided", status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): try: position_type_name = 'Practice' position_type = PositionType.objects.get(name=position_type_name) questions = Question.objects.filter(position_type=position_type.id) except PositionType.DoesNotExist: raise Http404 if len(questions) > 5: # generate random numbers randnums = random.sample(range(len(questions)), 5) # create new question list with the random numbers random_questions = [] for index in randnums: random_questions.append(questions[index]) serializer = QuestionSerializer(random_questions, many=True) return Response(serializer.data) else: serializer = QuestionSerializer(questions, many=True) return Response(serializer.data)
def ops_view_uniformity(self): # related_obj_type = self.request.GET.get("related_obj_type", None) # related_obj_id = self.request.GET.get("related_obj_id", None) # if related_obj_type is None or related_obj_id is None: # return ErrorCode.INVALID_INPUT, None smfrqs = SM.objects.filter_active( related_obj_type=self.related_obj_type, related_obj_id=self.related_obj_id) if not smfrqs.exists(): return ErrorCode.SURVEY_MODEL_SUBSTANDARD_NOT_RELATED_QUESTION, None # smrf = smfrqs[0] question_ids = SQ.objects.filter_active( model_facet_relation_id__in=smfrqs.values_list("id", flat=True), escape_task_id=self.task_id ).values_list("question_id", flat=True) questions = Question.objects.filter_active(id__in=question_ids, question_category=Question.CATEGORY_UNIFORMITY) question_data = QuestionSerializer(instance=questions, many=True).data return ErrorCode.SUCCESS, {"question_data": question_data}
class SurveySerializer(ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Survey fields = '__all__' def create(self, validated_data): question_data = validated_data.pop('questions') survey = Survey.create(**validated_data) for question in question_data: # TODO CONTINUE FROM HERE # COMPLEX NESTED OBJECT. import pdb; pdb.set_trace() #DEBUG return survey
def get(self, request, format=None): queryset = self.get_questions() serializer = QuestionSerializer(queryset, many=True) return Response(data=serializer.data, status=status.HTTP_404_NOT_FOUND)
class QuestionRamdomList(APIView): schema = ManualSchema(fields=[ coreapi.Field("position_type", required=True, location="path", schema=coreschema.String()), coreapi.Field("position_sub_type", required=False, location="path", schema=coreschema.String()), ]) position_type_param = openapi.Parameter( 'position_type', openapi.IN_QUERY, description="position type name parameter", type=openapi.TYPE_STRING) # filter_backends = (SimpleFilterBackend,) """ Retrieve 5 questions randomly. """ @swagger_auto_schema(manual_parameters=[position_type_param], responses={200: QuestionSerializer(many=True)}) def get(self, request, format=None): try: position_type_name = request.query_params.get( 'position_type') #request.query_params.get('position_type') position_sub_type_name = request.query_params.get( 'position_sub_type' ) #request.query_params.get('position_type') if not position_type_name: questions = Question.objects.all() else: position_type = PositionType.objects.get( name__iexact=position_type_name) if not position_sub_type_name: print('===== filter question: ', position_type.id) questions = Question.objects.filter( position_type=position_type.id) else: questions = Question.objects.filter( position_type=position_type.id).filter( position_sub_type=position_sub_type_name) except PositionType.DoesNotExist: raise Http404 if len(questions) > 5: # generate random numbers randnums = random.sample(range(len(questions)), 5) # create new question list with the random numbers random_questions = [] for index in randnums: random_questions.append(questions[index]) serializer = QuestionSerializer(random_questions, many=True) return Response(serializer.data) else: serializer = QuestionSerializer(questions, many=True) return Response(serializer.data)
def post(self, request, format=None): serializer = QuestionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): category = Question.objects.all() serializer = QuestionSerializer(category, many=True) return Response(serializer.data, headers={'Access-Control-Allow-Origin': '*'})
def get(self, request, pk, format=None): question_item = self.get_object(pk) serializer = QuestionSerializer(question_item) return Response(serializer.data)