Django-rest-framework "groupby" Modelserializer
I have the following situation class MyModel(models.Model): key = models.CharField(max_length=255) value = models.TextField(max_length=255) category = models.CharField(
Solution 1:
There is module that allows you to group Django models and still work with a QuerySet in the result: https://github.com/kako-nawao/django-group-by
Using the above to form your queryset:
# Postgres specific!from 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 then access the properties key
, category
and mode_list
on the resulting QuerySet items as attributes like qs[0].mode_list
. Therefore, in your serializer you can simply name them as fields.
The model_list
field might require a SerializerMethodField
with some custom code to transform the list.
Note that you need an aggregation if you don't want to group by mode
, as well.
Post a Comment for "Django-rest-framework "groupby" Modelserializer"