【问题标题】:How to serialize the django-mptt efficiently with Django Rest Framework?如何使用 Django Rest Framework 有效地序列化 django-mptt?
【发布时间】:2021-07-07 17:52:34
【问题描述】:

序列化器.py

class RecursiveField(serializers.Serializer):
    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data

class CategorySerializer(serializers.ModelSerializer):
    children = RecursiveField(many=True)
    class Meta:
        model = Category
        fields=('id', 'title', 'description', 'children',)

它返回如下响应数据:

    {
      "id": 1,
      "title": "Bike",
      "description": "",
      "children": []
    },
    {
      "id": 2,
      "title": "Car",
      "description": "",
      "children": [
        {
          "id": 3,
          "title": "Honda",
          "description": "",
          "children": []
        }
      ]
    },
    {
      "id": 3,
      "title": "Honda",
      "description": "",
      "children": []
    }

如上所示,ID为3的类别已重复。如果一个类别是某个类别的子类别,那么我不希望它再次单独显示。 我想要这样的响应数据:

    {
      "id": 1,
      "title": "Bike",
      "description": "",
      "children": []
    },
    {
      "id": 2,
      "title": "Car",
      "description": "",
      "children": [
        {
          "id": 3,
          "title": "Honda",
          "description": "",
          "children": []
        }
      ]
    }

有人可以帮我解决吗?

【问题讨论】:

    标签: django-rest-framework django-mptt


    【解决方案1】:

    你可以只返回根,所以只返回根而不是父母的孩子,我就是这样做的。

    class CategoryManager(TreeManager):
        def viewable(self):
            queryset = self.get_queryset().filter(level=0)
            return queryset
    

    Category 模型中。

    objects = CategoryManager()
    

    然后在views我这样使用它:

    queryset = Category.objects.viewable()
    

    【讨论】:

      猜你喜欢
      • 2015-01-20
      • 2018-06-05
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      相关资源
      最近更新 更多