I have a Category model that is a MPTT model. It is m2m to Group and I need to serialize the tree with related counts, imagine my Category tree is this:
Root (related to 1 group)
- Branch (related to 2 groups)
- Leaf (related to 3 groups)
...
So the serialized output would look like this:
{
id: 1,
name: 'root1',
full_name: 'root1',
group_count: 6,
children: [
{
id: 2,
name: 'branch1',
full_name: 'root1 - branch1',
group_count: 5,
children: [
{
id: 3,
name: 'leaf1',
full_name: 'root1 - branch1 - leaf1',
group_count: 3,
children: []
}]
}]
}
This is my current super inefficient implementation:
Model
class Category(MPTTModel):
name = ...
parent = ... (related_name='children')
def get_full_name(self):
names = self.get_ancestors(include_self=True).values('name')
full_name = ' - '.join(map(lambda x: x['name'], names))
return full_name
def get_group_count(self):
cats = self.get_descendants(include_self=True)
return Group.objects.filter(categories__in=cats).count()
View
class CategoryViewSet(ModelViewSet):
def list(self, request):
tree = cache_tree_children(Category.objects.filter(level=0))
serializer = CategorySerializer(tree, many=True)
return Response(serializer.data)
Serializer
class RecursiveField(serializers.Serializer):
def to_native(self, value):
return self.parent.to_native(value)
class CategorySerializer(serializers.ModelSerializer):
children = RecursiveField(many=True, required=False)
full_name = serializers.Field(source='get_full_name')
group_count = serializers.Field(source='get_group_count')
class Meta:
model = Category
fields = ('id', 'name', 'children', 'full_name', 'group_count')
This works but also hits the DB with an insane number of queries, also there's additional relations, not just Group. Is there a way to make this efficient? How can I write my own serializer?