类别子类别未正确显示 drf django

huangapple go评论77阅读模式
英文:

category subcategory not showing properly drf django

问题

I have this category models:

class Category(MPTTModel):
    name = models.CharField(max_length=100)
    slug = models.SlugField()
    parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE, db_index=True)

    class MPTTMeta:
        unique_together = ('slug', 'parent')
        verbose_name_plural = "categories"
        order_insertion_by = ['name']

    def __str__(self):
        full_path = [self.name]
        k = self.parent
        while k is not None:
            full_path.append(k.name)
            k = k.parent
        return ' -> '.join(full_path[::-1])

Serializers.py:

# category Listing Api

class CategorySerializers(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name', 'slug', 'children')

    def get_fields(self):
        fields = super().get_fields()
        fields['children'] = CategorySerializer(many=True, read_only=True)
        return fields

Views.py:

class CategoryView(generics.ListCreateAPIView):
    queryset = Category.objects.filter(parent__isnull=True)
    serializer_class = CategorySerializers

Currently, it's working, but I want to show subcategories inside categories only, not as main categories. As you can see, subcategories are listed inside main categories and with main categories also.

I am expecting this result:

[
    {
        "id": 1,
        "name": "Animals & Wildlife",
        "slug": "animals_wildlife",
        "children": []
    },
    {
        "id": 2,
        "name": "main cat",
        "slug": "mai_cat",
        "children": [
            {
                "id": 3,
                "name": "sub_cat",
                "slug": "submaincat",
                "children": []
            }
        ]
    },
    {
        "id": 4,
        "name": "maincat2",
        "slug": "maincat2",
        "children": [
            {
                "id": 5,
                "name": "submaincat2",
                "slug": "submaincat2",
                "children": []
            }
        ]
    },
    {
        "id": 6,
        "name": "maincat3",
        "slug": "maincat3",
        "children": []
    }
]

Please let me know if you need any further assistance.

英文:

i have this category models:

class Category(MPTTModel):
      name = models.CharField(max_length = 100)
      slug = models.SlugField()   
      parent = TreeForeignKey('self',blank=True, null=True, related_name='children', on_delete=models.CASCADE, db_index = True)


     class MPTTMeta:
           unique_together = ('slug', 'parent') 
           verbose_name_plural = "categories"
           order_insertion_by = ['name']

    def __str__(self):  
        full_path = [self.name]       
        k = self.parent       
        while k is not None:
              full_path.append(k.name)
               k = k.parent
        return ' -> '.join(full_path[::-1])

serializers.py:

category Listing Api

class CategorySerializers(serializers.ModelSerializer):
      class Meta:
            model = Category
            fields = ('id','name','slug','children')

      def get_fields(self):
          fields = super().get_fields()
          fields['children'] = CategorySerializer(many=True, read_only=True)
         return fields

views.py:

class CategoryView(generics.ListCreateAPIView):
      queryset = Category.objects.filter(parent__isnull=True)
      serializer_class = CategorySerializers

currently its working but i want to show subcategory inside category only not as a main category as you can see subcategory are listed inside main category and with maincategory also

类别子类别未正确显示 drf django

I am expecting this result:

   [
   {
        "id": 1,
        "name": "Animals & Wildlife",
        "slug": "animals_wildlife",
        "children": []
   },
   {
        "id": 2,
        "name": "main cat",
        "slug": "mai_cat",
        "children": [
        {
            "id": 3,
            "name": "sub_cat",
            "slug": "submaincat",
            "children": []
        }
    ]
   },

{
    "id": 4,
    "name": "maincat2",
    "slug": "maincat2",
    "children": [
        {
            "id": 5,
            "name": "submaincat2",
            "slug": "submaincat2",
            "children": []
        }
    ]
},

{
    "id": 6,
    "name": "maincat3",
    "slug": "maincat3",
    "children": []
}
]

...............................................

答案1

得分: 1

将您的视图集更改为

class CategoryViewSet(ModelViewSet):
    queryset = Category.objects.filter(parent__isnull=True)
    serializer_class = CategorySerializer

和序列化器更改为

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name', 'slug')

    def get_fields(self):
        fields = super().get_fields()
        fields['children'] = CategorySerializer(many=True, read_only=True)
        return fields
英文:

Change your viewset to

 class CategoryViewSet(ModelViewSet):
     queryset = Category.objects.filter(parent__isnull=True)
     serializer_class = CategorySerializer

and serializer to

 class CategorySerializer(serializers.ModelSerializer):

     class Meta:
         model = Category
         fields = ('id', 'name', 'slug')

     def get_fields(self):
         fields = super().get_fields()
         fields['children'] = CategorySerializer(many=True, read_only=True)
         return fields

huangapple
  • 本文由 发表于 2020年1月3日 16:09:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定