I'm trying to return an alternative json representation of a collection instead of a flat array when multiple IDs are provided in the querystring to make things more pleasant for parsing on the client. Unfortunately returning a dict instead of a queryset seems to break things, and presumably I need a custom serializer of some kind for this.
class Item(models.Model):
CATEGORY_CHOICES = (
('CATAGORY1', 'Category 1'),
('CATAGORY2', 'Category 2'),
)
text = models.TextField(max_length=300)
category = models.CharField(max_length=23, choices=CATEGORY_CHOICES)
class ItemList(generics.ListCreateAPIView):
"""
API endpoint represents list of items.
Supports GET and POST
"""
model = Item
serializer_class = ItemSerializer
def get_queryset(self):
"""
Return queryset filtered by id(s).
"""
queryset = Item.objects.order_by('category')
# queryset: [<'item', 'category1'>, <'item2', 'category1'>, <'item3', 'category2'>]
# if multiple ids are specified in querystring, return a dict instead
item_ids = self.request.QUERY_PARAMS.get('ids', None)
if item_ids is not None:
self.paginate_by = None
queryset = queryset.filter(id__in=(map(int, item_ids.split(','))))
# unideal queryset representation looks like:
# [{'item1', 'category1'}, {'item2', 'category1'}, {'item3', 'category2'}]
# improve representation of objects for frontend with a defaultdict
# e.g. { category1: [item, item2], category2: [item3] }
item_dict = defaultdict(list)
for item in queryset:
item_dict[item.category].append(item)
return item_dict
return queryset