Django REST,ModelField _get_val_from_obj

时间:2015-01-08 16:01:58

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

由于这个原因,我一直在拉头发。在我的案例中,ModelField似乎是一个不错的选择,但我似乎无法让它发挥作用。我正在为一个项目开发一个搜索引擎。

serializers.py

class FullSearchSerializer(serializers.Serializer):
    profiles = serializers.ModelField(model_field=Profiles())
    cv = serializers.ModelField(model_field=CV())

我得到了这个奇妙的错误:

'Profiles' object has no attribute '_get_val_from_obj'

我这样做的原因是因为我在序列化之前获取,列出和分页了几个模型。因此:(views.py)

result_list = []
            for target in targets:
                result = targets[target]['model'].objects.select_related().filter(reduce(operator.or_, targets[target]['query_list']) & targets[target]['extra_query'])
                if result:
                    result_list.append(result)
            print result_list
            results = list(
                sorted(
                    chain(*result_list),
                    key = lambda objects: objects.id,
                )
            )
            print results
            page = request.QUERY_PARAMS.get('page')
            paginated_result = paginate(results, page)
            serializer_context = {'request': request}
            serialized = PaginatedSearchSerializer(paginated_result, context=serializer_context)
            print serialized.data
            return JSONResponse(serialized.data, status=status.HTTP_200_OK)
        return JSONResponse({'message': 'No results'})

"目标[靶标] ['模型']"等等来自我循环的字典,获得正确的模型,序列化器等等。由于我正在创建一个能够搜索所有内容的函数,而不指定目标,我需要一个可以处理它的序列化程序。

完整的搜索类:

class Search(APIView):
    @method_decorator(req_login)
    @transaction.non_atomic_requests
    def get(self, request, *args, **kwargs):
        """ Defining variables """
        count_result = 0
        result = None
        target = None
        serialized = None
        search_query = ''
        result_list = {}
        """ Checks so values are there. """
        if 'target' in kwargs:
            target = kwargs['target']
        if 'q' in request.GET:
            search_query = request.GET['q']

        """ List of modeltions and methods for search. """
        targets = {
            'user': {
                'model': Profiles,
                'query_list': [
                    Q(profiledata__full_name__icontains=search_query)
                ],
                'extra_query': Q(profiledata__role__role='applicant'),
                'serializer': PaginatedProfileSerializer
            },
            'cv': {
                'model': CV,
                'query_list': [
                    Q(skills__icontains=search_query), 
                    Q(education__icontains=search_query),
                    Q(experience__icontains=search_query),
                    Q(interests__icontains=search_query),
                    Q(languages__icontains=search_query),
                    Q(driverlicense__icontains=search_query)
                ],
                'extra_query': Q(),
                'serializer': CVSerializer
            },
            'corporation': {
                'model': Corporation,
                'query_list': [
                    Q(name__icontains=search_query),
                    Q(description__icontains=search_query),
                    Q(keywords__title__icontains=search_query)
                ],
                'extra_query': Q(),
                'serializer': PaginatedCorporationSerializer
            },
            'jobs': {
                'model': Jobs,
                'query_list': [
                    Q(title__icontains=search_query),
                    Q(description__icontains=search_query),
                    Q(keywords__title__icontains=search_query)
                ],
                'extra_query': Q(),
                'serializer': PaginatedJobSerializer
            }
        }

        """ Making stuff happen and returns result """
        if target:
            result = targets[target]['model'].objects.select_related().filter(reduce(operator.or_, targets[target]['query_list']) & targets[target]['extra_query'])
            if result:
                count_result = result.count()
                page = request.QUERY_PARAMS.get('page')
                paginated_result = paginate(result, page)
                serializer_context = {'request': request}
                serialized = targets[target]['serializer'](paginated_result, context=serializer_context, many=True)
                return JSONResponse({'query': serialized.data, 'count': count_result}, status=status.HTTP_200_OK)
        else:
            result_list = []
            for target in targets:
                result = targets[target]['model'].objects.select_related().filter(reduce(operator.or_, targets[target]['query_list']) & targets[target]['extra_query'])
                if result:
                    result_list.append(result)
            print result_list
            results = list(
                sorted(
                    chain(*result_list),
                    key = lambda objects: objects.id,
                )
            )
            print results
            page = request.QUERY_PARAMS.get('page')
            paginated_result = paginate(results, page)
            serializer_context = {'request': request}
            serialized = PaginatedSearchSerializer(paginated_result, context=serializer_context)
            print serialized.data
            return JSONResponse(serialized.data, status=status.HTTP_200_OK)
        return JSONResponse({'message': 'No results'})

0 个答案:

没有答案