How to get parent node name while using django mptt package in django rest serializers?

511 views Asked by At

I am only getting parent id with this code, but i need parent node name . Is it possible to get parent node name ?

class Department(MPTTModel,NameStatusModelMixin):
    desc = models.TextField(blank=True, null=True, default=None)
    slug = models.SlugField(max_length=100, blank=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
    related_positions = models.ManyToManyField('Position', related_name='departments')
    
    
    class MPTTMeta:
        order_insertion_by = ['id']
 

    def __str__(self):
        return self.name

class DepartmentDetailSerializer(ModelSerializer):
    
    class Meta:
        model = Department
        fields = ('id', 'name', 'status', 'slug', 'desc', 'parent')
1

There are 1 answers

0
Chris On BEST ANSWER

Easiest way is:

class ParentSerializer(ModelSerializer):
    class Meta:
        model = Department
        fields = ('name')

class DepartmentDetailSerializer(ModelSerializer):

    parent = ParentSerializer()
    
    class Meta:
        model = Department
        fields = ('id', 'name', 'status', 'slug', 'desc', 'parent')

You can also look at using a SerializerMethodField or a recursive/self-referential serializer depending your exact needs/what you want the end data to look like...