How to set Serializer for displaying parent and children as a list DRF?

I'm making an app which is about News News have an attribute called Category which can be nested For example: Human: --BodyOrgans: ----Hand Just to make the issue more clear We need to prepare a way so when making news when we choose Human category,we can access the child which is "BodyOrgan" and when choosing this, accessing "Hand" or other children it might have This is my models file:

```
class News(models.Model):
    PUBLISH_STATUS = (
        ('P', 'Published'),
        ('W', 'Waiting for approval'),
        ('D', 'Draft'),
    )
    title = models.CharField(max_length=255)
    slug = models.SlugField(null=True, blank=True)
    sign_image = models.ImageField(upload_to='images', null=True, blank=True)
    summary = models.TextField(null=True, blank=True)
    description = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    publish_status = models.CharField(max_length=1, choices=PUBLISH_STATUS, default='D')
    publish_time = models.TimeField(null=True, blank=True, default=None)
    publish_date = models.DateTimeField(null=True, blank=True, default=None)
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    category = models.ManyToManyField('Category')
    tag = models.ManyToManyField('Tag')

    def __str__(self):
        return self.title


class Category(models.Model):
    PUBLISH_CHOICES = (
        ('A', 'Active'),
        ('I', 'Inactive'),
    )
    parent = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, blank=True)
    name = models.CharField(max_length=50, null=True)
    publish_status = models.CharField(max_length=1, choices=PUBLISH_CHOICES, default='A')
    description = models.TextField(null=True, blank=True)
    tag = models.ManyToManyField('Tag')

    def __str__(self):
        return self.name
```

And also Serializer:

class CategorySerializer(ModelSerializer):
    class Meta:
        model = Category
        fields = ['name', 'parent']

    list = ListSerializer(
        fields=['name', 'parent'],
        source='get_parent'
    )

    @staticmethod
    def get_parent(obj):
        return obj.parent.name



class NewsSerializer(ModelSerializer):

    @staticmethod
    def get_title_slug(instance):
        return slugify(instance.title)

    @staticmethod
    def get_user(obj):
        return obj.author.username

    slug = SerializerMethodField(method_name='get_title_slug', read_only=True)
    author = SerializerMethodField(method_name='get_user')

    class Meta:
        model = News
        fields = '__all__'
        category = CategorySerializer()
        read_only_fields = ['author', 'publish_date', 'publish_time']

I'd be greatful if you could help me out _/_

If you are trying to get categories with their children, first use related_name to access children easier:

parent = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, blank=True, related_name="children")

Then you can access a category children via children key.

Now just use a nested serializer:

class CategoryChildrenSerializer(serializer.ModelSerializer):

    class Meta:
        model = Category
        fields = [...]


class CategorySerializer(ModelSerializer):
    children = CategoryChildrenSerializer(many=True)
    
    class Meta:
        model = Category
        fields = [..., "children"]
Back to Top