I serialise Django Haystack's SearchQueryStack with DRF as following, and in resulting JSON response i want to get rid of object wrapper around my Post model:
{
"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": {...
This is JSON i want (there is no 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": {...
This is view:
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
Here are serializers:
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
Here is 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')
As you can see closest I could get is to rename 'object' wrapper to 'postWrapper'. I want to remove it completely as a wrapper, so there'd be only Post model list inside 'results', which contains 'hitcount', 'id', 'content', 'owner' etc...
Any help is much appreciated. Thanks in advance.
So I added this to my PostSearch view and it solved my issue:
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
Basically I made a new list without 'object' wrapper and put it back to return value.