摆脱django rest框架序列化SearchQuerySet中的“对象”包装器

时间:2015-03-10 16:47:16

标签: django-rest-framework django-haystack

我使用DRF将Django Haystack的SearchQueryStack序列化如下,在得到的JSON响应中,我希望摆脱Post模型周围的对象包装:

{
"count": 6, 
"next": null, 
"previous": null, 
"start_index": 1, 
"end_index": 6, 
"num_pages": 1, 
"results": [
    {
        "postWrapper": {
            "hitcount": {
                "counter": 9, 
                "id": 251
            }, 
            "id": 277, 
            "content": "test", 
            "owner": {...

这是我想要的JSON(没有postWrapper):

    {
"count": 6, 
"next": null, 
"previous": null, 
"start_index": 1, 
"end_index": 6, 
"num_pages": 1, 
"results": [
    {
            "hitcount": {
                "counter": 9, 
                "id": 251
            }, 
            "id": 277, 
            "content": "test", 
            "owner": {...

这是观点:

class PostSearch(generics.ListAPIView):
model = Post

def get(self, request, *args, **kwargs):
    # simplified filtering of an SQS
    q = request.GET.get('q')
    sqs = SearchQuerySet().filter(content=q)
    paginator = Paginator(sqs, 10)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page
        posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        posts = paginator.page(paginator.num_pages)

    serializer_context = {'request': request}
    serializer = PaginatedPostSerializer(posts, context=serializer_context)
    ret = serializer.data

    return response.Response(ret)

class SearchSerializer(serializers.Serializer):
object = PostSerializer()

def to_representation(self, obj):
    """
    Object instance -> Dict of primitive datatypes.
    """
    ret = OrderedDict()
    fields = [field for field in self.fields.values() if not field.write_only]

    for field in fields:
        try:
            attribute = field.get_attribute(obj)
            if field.field_name == 'object':
                field.field_name = 'postWrapper'
        except SkipField:
            continue

        if attribute is not None:
            ret[field.field_name] = field.to_representation(attribute)

    return ret

以下是序列化程序:

class SearchSerializer(serializers.Serializer):
    object = PostSerializer()

    def to_representation(self, obj):
        """
        Object instance -> Dict of primitive datatypes.
        """
        ret = OrderedDict()
        fields = [field for field in self.fields.values() if not field.write_only]

        for field in fields:
            try:
                attribute = field.get_attribute(obj)
                if field.field_name == 'object':
                    field.field_name = 'postWrapper'
            except SkipField:
                continue

            if attribute is not None:
                ret[field.field_name] = field.to_representation(attribute)

        return ret


class PaginatedPostSerializer(pagination.PaginationSerializer):

    start_index = serializers.SerializerMethodField()
    end_index = serializers.SerializerMethodField()
    num_pages = serializers.ReadOnlyField(source='paginator.num_pages')

    class Meta:
        object_serializer_class = SearchSerializer

    def get_start_index(self, page):
        return page.start_index()

    def get_end_index(self, page):
        return page.end_index()

    def get_curr_page(self, page):
        return page.number

这是PostSerializer:

class PostSerializer(serializers.ModelSerializer):
    owner = UserSerializer(required=False, read_only=True)
    category_edit = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), write_only=True)
    category = CategorySerializer(read_only=True)
    price = serializers.CharField()
    price_currency = serializers.CharField()
    hitcount = serializers.SerializerMethodField()
    images = ImageSerializer(many=True, read_only=True)

    def get_hitcount(self, context):
        # Content_type for Post is 20
        c_type = ContentType.objects.get_for_model(context)
        obj, created = HitCount.objects.get_or_create(content_type=c_type, object_pk=context.id)
        data = {}
        data["id"] = obj.pk
        data["counter"] = obj.hits
        return data

    class Meta:
        model = Post
        fields = ('hitcount', 'id', 'content', 'owner', 'category', 'category_edit', 'images', 'price', 'price_currency')

正如你所看到的,我能得到的最接近的是重命名'对象'包装到' postWrapper'。我想完全删除它作为一个包装器,所以只有在结果'里面包含' hitcount',' id' ,'内容','所有者'等...

非常感谢任何帮助。提前谢谢。

2 个答案:

答案 0 :(得分:0)

我认为只需使用PostSerializer,因为object_serializer_class中的PaginatedPostSerializer就是您想要的。

class PaginatedPostSerializer(pagination.PaginationSerializer):
      class Meta:
            object_serializer_class = PostSerializer

如果您想覆盖to_representation,可以扩展 PostSerializers,而不是将其作为新字段添加到新的序列化程序中。

ps:如果你想在postWrapper中包装结果项,你不需要覆盖to_representation函数,你可以在SearchSerializer中重命名它:

class SearchSerializer(serializers.Serializer):
    # object = PostSerializer()
    # rename the object to what you want
    postWrapper = PostSerializer() 

我认为我对你的查询集有误解,所以请在上面做出答案。

class SearchSerializer(serializers.Serializer):
    object = PostSerializer()

    def to_representation(self, instance):
        res = super(SearchSerializer, self).to_representation(instance)
        # pop of the object field, and push the fields inside the object to parent level
        objectfield = res.pop('object', None)
        if objectfield:
            for field, value in objectfield.iteritems():
                res[field] = value
        return res

恕我直言,要将您的查询集更改为Post模型查询集,并将paginatedSerializer的object_serializer_class设置为PostSerializer更有意义。

答案 1 :(得分:0)

所以我将此添加到我的PostSearch视图中,它解决了我的问题:

    ret = serializer.data
    new_result_list = []
    results = ret.get('results')
    for orderedDict in results:
        post = orderedDict.get('object')
        new_result_list.append(post)

    ret['results'] = new_result_list

基本上我创建了一个没有'对象'包装并将其放回到返回值。