djangodjango-rest-frameworkdjango-mptt

'TreeQuerySet' object has no attribute 'name'


I have a Problem in Converting the' TreeQuerySet' object to the QuerySet object

This is the error I am getting While serializing using DRF

Got AttributeError when attempting to get a value for field name on serializer SubCategoriesSerializer. The serializer field might be named incorrectly and not match any attribute or key on the TreeQuerySet instance. Original exception text was:

'TreeQuerySet' object has no attribute 'name'.

Serializer

class SubCategorySerializer(serializers.ModelSerializer):
  
    class Meta:
        model = Category
        fields = ('id',
            'name',
            'slug',
            'views',
            'title',
            'description',
            'avatar',
            'color'
            )

Api Views

category = Category.objects.get(pk=1)
categories = category.get_children()
categories_serializer = SubCategorySerializer(categories, context={'request': request})

Solution

  • TreeQuerySet is in fact a subclass of QuerySet

    categories = category.get_children()
    

    returns multiple Category objects but you are trying to serialize single instance, instead you should serialize a QuerySet with additional parameter in serializer many=true

    categories_serializer = SubCategorySerializer(categories, many=true, context={'request': request})