Home > Blockchain >  How to display category and subcategory in post serializer django-rest-framework
How to display category and subcategory in post serializer django-rest-framework

Time:10-14

I need to extract categories and subcategories in Post serializer, because I need to put pagination, if I put pagination in category view, different amount of posts will come, so I need to put pagination in Post view, I need to return response so that it looks like this

and I want to create rest api to return nested json like this

[
{
  "id": 1,
  "title": "Taomlar",
  "subcat": [
      {
        id: 2,
        title: "Milliy",
        post: [
            {
              id: 1,
              title: 'Palov',
              summa: 300000,
              ...
            },     
              {
              id: 2,
              title: 'Palov',
              summa: 300000,
              ...
            },
          ]
      },     
    ]  
}     
]

models.py

class Category(Base):
    title = models.CharField(max_length=200)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    def __str__(self):
        return self.title

class Post(Base):
    title = models.CharField(max_length=225)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='post')

serializers.py

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'

class PostSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Post
        fields = '__all__'

Can anyone please give me the solution for this problem

CodePudding user response:

you can read more about nested serializer in Django Rest Framework

you should make it in this way

class CategorySerializer(serializers.ModelSerializer):
      post_serializer = PostSerializer(many=True)
      class Meta:
          model = Category
          fields = ['your_field', 'post_serializer']

this a basic example, try to read more about it to know how you can implement nested relations

CodePudding user response:

As much as I understand you need to get each Category with it's related posts.

Overwriting like this :


class CategorySerializer(serializers.ModelSerializer):
    posts = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = (
            'id',
            'title',
            'posts',
        )
    def get_posts(self, obj):
        serializer = PostSerializer(obj.products.all(), context=self.context, many = True)
        return serializer.data
  • Related