python 2.7 - Django-REST-Framework "GroupBy" ModelSerializer -
i have following situation
class mymodel(models.model): key = models.charfield(max_length=255) value = models.textfield(max_length=255) category = models.charfield(max_length=4) mode = models.charfield(max_length=4)
the fields key
, category
, mode
unique together. have following objects:
m1 = mymodel(key='model_key', value='1', category='cat_1' mode='mode_1') m2 = mymodel(key='model_key', value='2', category='cat_1' mode='mode_2') m3 = mymodel(key='model_key', value='1', category='cat_2' mode='mode_1') m4 = mymodel(key='model_key', value='2', category='cat_2' mode='mode_2')
i want expose api group key
, category
serialized data this:
{ "key": "model_key", "category": "cat_1" "mode_1": { "id": 1, "value": "1" } "mode_2": { "id": 2, "value": "2" } }, { "key": "model_key", "category": "cat_2" "mode_1": { "id": 3, "value": "1" } "mode_2": { "id": 4, "value": "2" } }
is there way of doing in django rest framework modelserializer
.
there module allows group django models , still work queryset in result: https://github.com/kako-nawao/django-group-by
using above form queryset:
# postgres specific! django.contrib.postgres.aggregates.general import arrayagg qs = mymodel.objects.group_by('key', 'category').annotate( mode_list=arrayagg('mode')).order_by( 'key', 'category').distinct()
you can access properties key
, category
, mode_list
on resulting queryset items attributes qs[0].mode_list
. therefore, in serializer can name them fields.
the model_list
field might require serializermethodfield
custom code transform list.
note need aggregation if don't want group mode
, well.
Comments
Post a Comment