Reputation: 115
I want to group a specific attributes from a model instead of serializing them individually more or less like this
class MyModel(models.Model):
attr1 = models.IntegerField()
attr2 = models.IntegerField()
attr3 = models.CharField()
and serialize will output this
{
# other attrs
"grouped_attrs" : {"attr1": 23, "attr2": 848, "attr3": "foo"}
# other attrs
}
Upvotes: 0
Views: 24
Reputation: 960
You can user SerializerMethodField for that.
from rest_framework import serializers
class MyModelSerializer(serializers.ModelSerializer):
grouped_attrs = serializers.SerializerMethodField()
class Meta:
model = MyModel
fields = ('grouped_attrs')
def get_grouped_attrs(obj):
return {
'attr1': obj.attr1,
'attr2': obj.attr2,
'attr3': obj.attr3
}
Upvotes: 1