My issue is related to Django RestFramework and is about how to group elements.
This is my serializers.py
from collaborativeAPP.models import *
from rest_framework import serializers
class VocabSerializer(serializers.ModelSerializer):
term_word = serializers.CharField(source='term.word',read_only=True)
kwdGroup = serializers.StringRelatedField()
class Meta:
model = Vocab
fields = ('id','term_word', 'meaning','kwdGroup')
class TermSerializer(serializers.ModelSerializer):
word = serializers.CharField(read_only=True)
class Meta:
model = Term
fields = ('url', 'word')
The following json it's the actual result:
{"results":[
{
"id": 5,
"term_word": "word1",
"meaning": "Text1"
"kwdGroup": "A"
},
{
"id": 6,
"term_word": "word2",
"meaning": "Text2"
"kwdGroup": "A"
},
{
"id": 7,
"term_word": "word3",
"meaning": "Text3"
"kwdGroup": "A"
}
]}
As you can notice "kwdGroup" is a repetitive element that i which to group.
I would like to group by kwdGroup
{"A":[
{
"id": 5,
"term_word": "word1",
"meaning": "Text1"
},
{
"id": 6,
"term_word": "word2",
"meaning": "Text2"
},
{
"id": 7,
"term_word": "word3",
"meaning": "Text3"
}
]
}
I'm looking for answers on http://www.django-rest-framework.org/ on api guide but i'm having difficulties to find an approach to lead with it. Do you share this same issue? Do you have any suggestion how can i do this? Do you have any example that deals with element grouping using Django RestFramework?
Thanks in advance.
One way to achieve this is to use a SerializerMethodField. The below might be slightly different than your use case, but you can adopt accordingly. There are other ways of achieving this as well, including overwriting
to_representation
methods, but they rely on messing with the inner workings of DRF more than is relevant here.models.py
serializers.py
An example
Let's assume that the
kwdGroup
field is the relation field to a model calledKeyWordGroup
.The default
ListSerializer
uses theto_representation
method to render a list of the serialized objects rest_framework :We can modify the
ListSerializer
to group the results for example:We can then use the modified
VocabListSerializer
with theVocabSerializer
.You might use "serializer relations", and especially "nested relationships". See documentation here