How to serialize hierarchical relationships in Django REST

I have a Django model hierarchical with django-mptt that looks like this:

class UOMCategory(MPTTModel, BaseModel): """ This represents categories of different unit of measurements. """ name = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='%(app_label)s_%(class)s_sub_uom_categories') 

Now the problem is creating the REST API using the Django REST Framework; How can I make sure the parent field returns serialized data?

Here is the Model Serializer:

 class UOMCategorySerializer(BaseModelSerializer): """ REST API Serializer for UOMCategory model """ class Meta: model = UOMCategory 
+7
python django serialization django-rest-framework django-mptt
source share
1 answer

In DRF, you can use a serializer as a field in another serializer. However, recursion is not possible.

Tom Christie posted a solution on another issue ( Django rest framework nested self-referencing objects ). Its solution will also work with your problem.

In your UOMCategorySerializer.Meta class, you specify the fields you want to use, also specify the parent and / or child fields. Then you use Tom Christie's solution.

In your case, this will give:

 class UOMCategorySerializer(ModelSerializer): class Meta: model = UOMCategory fields = ('name', 'description', 'parent', 'children') 

Tom Christies solution: By specifying which field to use for parents and / or children, you avoid using too large (and possibly infinite) recursion:

 UOMCategorySerializer.base_fields['parent'] = UOMCategorySerializer() UOMCategorySerializer.base_fields['children'] = UOMCategorySerializer(many=True) 

The above works for me in a similar situation.

+7
source share

All Articles