How to serialize hierarchical relationship in Django REST

大憨熊 提交于 2019-12-21 00:00:12

问题


I have a Django model that is hierarchical using django-mptt, which looks like:

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')

The problem now is I created a REST API using Django REST Framework; how do I make sure that parent field returns serialized data?

Here is the Model Serializer:

class UOMCategorySerializer(BaseModelSerializer):
    """
    REST API Serializer for UOMCategory model
    """
    class Meta:
        model = UOMCategory

回答1:


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 question (Django rest framework nested self-referential objects). His solution will also work with your problem.

In your UOMCategorySerializer.Meta class you specify the fields you want to use, also list the parent and/or children field(s) there. Then you use Tom Christies solution.

In your case this would give:

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

Tom Christies solution: By specifying what field to use for parent and/or children, you avoid using too much (and possibily endless) recursion:

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

The above works for me in a similar situation.



来源:https://stackoverflow.com/questions/21112302/how-to-serialize-hierarchical-relationship-in-django-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!