json - Django RestFramework group by -
my issue related django restframework , how group elements.
this serializers.py
from collaborativeapp.models import * 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 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 can notice "kwdgroup" repetitive element group.
i group 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 answers on http://www.django-rest-framework.org/ on api guide i'm having difficulties find approach lead it. share same issue? have suggestion how can this? have example deals element grouping using django restframework?
thanks in advance.
one way achieve use serializermethodfield. below might different use case, can adopt accordingly. there other ways of achieving well, including overwriting to_representation
methods, rely on messing inner workings of drf more relevant here.
models.py
class dictionary(model): id = primarykey class word(model): dictionary = foreignkey(dictionary, related_name='words') word = charfield() group = charfield()
serializers.py
class wordserializer(serializers.modelserializer): word = serializers.charfield(read_only=true) class meta: model = word fields = ('word',) class dictionaryserializer(serializers.modelserializer): group_a = serializers.serializermethodfield() group_b = serializers.serializermethodfield() def get_group_a(self, instance): return wordserializer(instance.words.filter(group='a'), many=true).data def get_group_b(self, instance): return wordserializer(instance.words.filter(group='b'), many=true).data class meta: model = dictionary fields = ('group_a', 'group_b')
an example
>>> my_dictionary = dictionary.objects.create() >>> word.objects.bulk_create( word(word='arrow', group='a' dictionary=my_dictionary), word(word='apple', group='a' dictionary=my_dictionary), word(word='baby', group='b' dictionary=my_dictionary), word(word='banana', group='b' dictionary=my_dictionary) ) >>> serializer = dictionaryserializer(my_dictionary) >>> print serializer.data { 'group_a': { 'word': 'arrow', 'word': 'apple' }, 'group_b': { 'word': 'baby', 'word': 'banana' }, }
Comments
Post a Comment